如何在GridView中添加CheckBox字段?
问题描述:
如何以编程方式在gridview中添加复选框字段,我的代码有什么问题?如何在GridView中添加CheckBox字段?
try
{
string [email protected]"Data Source=A-63A9D4D7E7834\SECOND;";
string [email protected]"Initial Catalog=replicate;";
string [email protected]"User ID=sa;";
string [email protected]"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属性的值。这应该与查询中的列名或别名相匹配。 (虽然我不认为复选框会与数字结果一起工作)。
编辑:没有意识到你正在尝试做什么。模板字段和常规复选框应该让你更接近你想要的东西。像这样?
例如
const int ColumnSelect = 0;
protected void Page_Load(object sender, EventArgs e)
{
//Get real data here.
DataTable dt = new DataTable();
dt.Columns.Add("count");
dt.Rows.Add(dt.NewRow());
dt.Rows[0][0] = "5";
GridView1.Columns.Add(new TemplateField());
BoundField b = new BoundField();
GridView1.Columns.Add(b);
b.DataField = "count";
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.Header)
{
e.Row.Cells[ColumnSelect].Controls.Add(new CheckBox());
}
}
编辑#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"
nope,这不起作用,它不应该与任何东西绑定 – user287745 2010-10-24 04:37:21
好吧,我现在看到。修改我的答案。 – Bitwise 2010-10-24 22:30:21
这个复选框会在选中时帮助我检测它所属的行吗? – user287745 2010-10-25 19:28:34