我在gridview中使用复选框..当点击复选框时,我的代码没有得到“IsChecked”值..这里是代码..
protected void ButtonDelete_Click(object sender, EventArgs e)
{
StringCollection sc = new StringCollection();
string id = string.Empty;
for (int i = 0; i < GridView1.Rows.Count; i++)//loop the GridView Rows
{
CheckBox cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1"); //find the CheckBox
if (cb != null)
{
if (cb.Checked)...//(showing ischecked=false)///
{
id = GridView1.Rows[i].Cells[1].Text; // get the id of the field to be deleted
sc.Add(id); // add the id to be deleted in the StringCollection
}
}
}
我将数据库中的数据删除为..
private void DeleteRecords(StringCollection sc)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = (ConfigurationManager.ConnectionStrings["MyDbConn"].ToString());
StringBuilder sb = new StringBuilder(string.Empty);
foreach (string item in sc)
{
const string sqlStatement = "DELETE FROM User WHERE user_id";
sb.AppendFormat("{0}='{1}'; ", sqlStatement, item);
}
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Deletion Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
我的asp代码是..
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Button ID="ButtonDelete" runat="server" Text="Delete" OnClick="ButtonDelete_Click" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="user_id" HeaderText="user_id" ReadOnly="True" />
<asp:BoundField DataField="fname" HeaderText="fname"/>
<asp:BoundField DataField="lname" HeaderText="lname"/>
</Columns>
</asp:GridView>
答案 0 :(得分:1)
我猜你在没有检查
的情况下在Page_Load上绑定你的网格Page.IsPostBack
条件。
If(!Page.IsPostBack)
BindGrid();
应该解决你的问题。