日期:2014-05-18  浏览次数:20414 次

asp.net中GridView能冲后台怎么在第一列添加Checkbox复选框?
如题。后台代码怎么写才能给前台绑定一个复选框???

  其它的列我已经用这种方法弄了
  foreach(DataColumn dc in dt.Columns)
  {
  ListItem li = new ListItem();
  li.DataField = dc.ColumnName;
  li.HearderText = (dc.ColumnName的中文名);
  this.GridView2.Columns.Add(li);
  }

  this.GridView2.DataSource = dt.DefaultView;
  this.GridView2.DataBind();

  但是那个CheckBoxField cbf = new CheckBoxField();  
  貌似不能出复选框啊???哪位高人指点下该怎么绑???

注意了:我前台什么也没写,就是依赖后台的代码动态生成绑定。。。。

------解决方案--------------------

http://leelei.blog.51cto.com/856755/236936
------解决方案--------------------
.GridView和CheckBox结合:
 
效果图:

 
后台代码:
 
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
 
public partial class Default5 : System.Web.UI.Page
{
//清清月儿http://blog.csdn.net/21aspnet 
SqlConnection sqlcon;
string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=sa";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind();
}
}
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (CheckBox2.Checked == true)
{
cbox.Checked = true;
}
else
{
cbox.Checked = false;
}
}
}
protected void Button2_Click(object sender, EventArgs e)
{
sqlcon = new SqlConnection(strCon);
SqlCommand sqlcom;
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (cbox.Checked == true)
{
 
string sqlstr = "delete from 飞狐工作室 where 身份证号码='" + GridView1.DataKeys[i].Value + "'";
sqlcom = new SqlCommand(sqlstr, sqlcon);
sqlcon.Open();
sqlcom.ExecuteNonQuery();
sqlcon.Close();
}
}
bind();
}
protected void Button1_Click(object sender, EventArgs e)
{
CheckBox2.Checked = false;
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
cbox.Checked = false;
}
}
public void bind()
{
string sqlstr = "select top 5 * from 飞狐工作室";
sqlcon = new SqlConnection(strCon);
SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
DataSet myds = new DataSet();
sqlcon.Open();
myda.Fill(myds, "tb_Member");
GridView1.DataSource = myds;
GridView1.DataKeyNames = new string[] { "身份证号码" };
GridView1.DataBind();
sqlcon.Close();
}
}
 
前台主要代码:
 
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False"