C# 如何在GridView中添加复选框字段?
如何以编程方式在gridview中添加复选框字段,我的代码有什么问题C# 如何在GridView中添加复选框字段?,c#,gridview,C#,Gridview,如何以编程方式在gridview中添加复选框字段,我的代码有什么问题 try { string Data_source=@"Data Source=A-63A9D4D7E7834\SECOND;"; string Initial_Catalog=@"Initial Catalog=replicate;"; string User=@"User ID=sa;"; string Password=@"Password=two"; string full_con=Data_sour
try
{
string Data_source=@"Data Source=A-63A9D4D7E7834\SECOND;";
string Initial_Catalog=@"Initial Catalog=replicate;";
string User=@"User ID=sa;";
string Password=@"Password=two";
string full_con=Data_source+Initial_Catalog+User+Password;
SqlConnection connection = new SqlConnection(full_con);
connection.Open();
SqlCommand numberofrecords = new SqlCommand("SELECT COUNT(*) FROM dbo.Table_1", connection);
DataSet ds2 = new DataSet();
SqlDataAdapter testadaptor = new SqlDataAdapter();
testadaptor.SelectCommand = new SqlCommand("SELECT COUNT(*) FROM dbo.Table_1", connection);
testadaptor.Fill(ds2);
grid1.DataSource = ds2;
CheckBoxField c = new CheckBoxField();
grid1.Columns.Add(c);
grid1.DataBind();
numberofrecords.Dispose();
connection.Close();
connection.Dispose();
}
catch (Exception a)
{
Response.Write("Please check ");
Response.Write(a.Message.ToString());
Response.Write(a.Source.ToString());
}//catch
CheckBoxField可能需要DataField属性的值。这应该与查询中的列名或别名匹配。(不过,我认为复选框不能用于数字结果。) 编辑:没有意识到你想做什么。模板字段和常规复选框会使您更接近所需内容。像这样的 e、 g 编辑#2:至于获取值,您当然可以这样做。您是在寻找Javascript还是服务器端解决方案?下面是一个简单的服务器端示例,如果您单击了按钮:
protected void Button1_Click(object sender, EventArgs e)
{
foreach(GridViewRow row in GridView1.Rows)
{
//Could also use (CheckBox)row.Cells[ColumnSelect].FindControl if you give the checkboxes IDs when generating them.
CheckBox cb = (CheckBox)row.Cells[ColumnSelect].Controls[0];
if (cb.Checked)
{
//Do something here.
}
}
}
我必须指定哪个复选框对象,如下所示
System.Web.UI.WebControls.CheckBox
我还必须将此添加到gridview aspx页面
OnRowDataBound="GridView1_RowDataBound"
不,这在这里不起作用,我现在明白了,它不应该和任何东西绑定在一起。修改了我的答案。选中此复选框是否有助于检测它所属的行?我添加了一个示例,说明如何在回发期间检索选中的值。然后可以以类似的方式获取行中的其他值。
OnRowDataBound="GridView1_RowDataBound"