How to Add the CheckBox Field in GridView?
How to add the checkbox field in gridview programatically, what's wrong with my code?
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.开发者_C百科Write(a.Message.ToString());
Response.Write(a.Source.ToString());
}//catch
The CheckBoxField will probably want a value for the DataField property. This should match the column names or aliases in your query. (I don't think a checkbox will work with number results, though.)
Edited: didn't realize what you were trying to do. A template field and a regular checkbox should get you closer to what you want. Something like this?
e.g.
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());
}
}
Edit #2: as for getting the value, you can certainly do this. Are you looking for a Javascript or server-side solution? Here's a simple example for server-side if you had a button click:
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.
}
}
}
I had to specify which checkbox object, like this
System.Web.UI.WebControls.CheckBox
Also I had to add this to the gridview aspx page
OnRowDataBound="GridView1_RowDataBound"
精彩评论