[英]How to Add the CheckBox Field in 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_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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.