如何在GridView中添加CheckBox字段?

时间:2010-10-23 21:16:01

标签: 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_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

2 个答案:

答案 0 :(得分:1)

CheckBoxField可能需要DataField属性的值。这应该与查询中的列名或别名匹配。 (但我不认为复选框可以使用数字结果。)

编辑:没有意识到你想要做什么。模板字段和常规复选框可以让您更接近您想要的。像这样的东西?

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());
    }
}

编辑#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.
        }
    }
}

答案 1 :(得分:0)

我必须指定哪个复选框对象,例如

        System.Web.UI.WebControls.CheckBox

我还必须将它添加到gridview aspx页面

       OnRowDataBound="GridView1_RowDataBound"