【发布时间】:2014-06-01 13:33:46
【问题描述】:
我的 web 表单上有一个 gridview,我在 gridview 的模板字段中选中了复选框。我希望如果在gridview中选中该复选框,它将在我的数据库列中插入1,如果未选中,则应插入0,即默认情况下该字段应插入0。 我试过这样做- 我的 aspx 页面-
<asp:GridView ID="GridMain" runat="server" Width="1000px"
AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Student Name">
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%# Eval("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Enable/Disable">
<ItemTemplate>
<asp:CheckBox ID="chkenbl" runat="server" AutoPostBack="True"
oncheckedchanged="chkenbl_CheckedChanged" />
<br />
<asp:Label ID="Label1" runat="server" Text='<%# Eval("id") %>' Visible="False"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
我的cs页面-
public void show()
{
try
{
dt = g1.return_dt("select id,name from tbl_data_show where en_dis='0' order by name");
if (dt.Rows.Count > 0)
{
adsource = new PagedDataSource();
adsource.DataSource = dt.DefaultView;
adsource.PageSize = 5;
GridMain.DataSource = adsource;
GridMain.DataBind();
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
protected void chkenbl_CheckedChanged(object sender, EventArgs e)
{
foreach (GridViewRow row in GridMain.Rows)
{
CheckBox chk = sender as CheckBox;
if (chk.Checked)
{
try
{
//Label lblid = (Label)GridMain.FindControl("Label1");
Label lblid = new Label();
lblid.Text = GridMain.FindControl("Label1").ToString();
rows=g1.ExecDB("insert into tbl_data_show(en_dis) values('1') where id="+lblid.Text);
if (rows > 0)
{
Response.Write("Rows Effected Successfull.");
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
else
{
//Label lblid1 = (Label)GridMain.FindControl("Label1");
Label lblid1 = new Label();
lblid1.Text = GridMain.FindControl("Label1").ToString();
rows=g1.ExecDB("insert into tbl_data_show(en_dis) values('0') where id="+lblid1.Text);
if (rows > 0)
{
Response.Write("Rows Effected Successfull.");
}
}
}
}
请指导我哪里出错了。我收到此异常“对象引用未设置为对象的实例。”。
【问题讨论】:
-
不要这样做:
rows=g1.ExecDB("insert into tbl_data_show(en_dis) values('1') where id="+lblid.Text);使用参数化 sql。你调试过你的代码吗?它会抛出异常吗?预期的行为是什么,观察到的行为是什么? -
那么您遇到的具体问题是什么?有例外吗?运行时 lblid.Text 的价值是什么? DB 中的 id 类型是什么(如果是 varchar,则应将值用引号括起来)。顺便说一句,Convert.ToInt32(bool) 可以减少你的代码量。
-
@DGibbs:是的,请检查我更新的问题。我已经提到我遇到了什么异常。
-
@d_z:请检查我的问题朋友。我已经更新了我的问题。请指导我哪里做错了?
-
@Omi,哪个语句产生异常?
标签: c# asp.net sql gridview checkbox