我的网络表单上有一个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.");
}
}
}
}
请指导我哪里出错了。我收到此异常“对象引用未设置为对象的实例。”。
答案 0 :(得分:1)
嗯,现在在得到一些细节后我可以说: 1)您的复选框具有autopostback = true,这将导致每次复选框点击后回发。在代码隐藏循环中抛出所有行并更新,因此每次单击任何复选框时都会更新所有行。 2)要获得Label.Text值,您可以尝试这样的事情:
CheckBox chkStatus = (CheckBox)sender;
GridViewRow row = (GridViewRow)chkStatus.NamingContainer;
Label lbl = (Label)row.FindControl("Label1");
string lblTxt = lbl.Text;
或者您可以将自定义属性添加到您的复选框(rid =“&lt;%#Eval(”id“)%&gt;”)并获取其值而不是隐藏标签:
string id = ((CheckBox)sender).Attributes["rid"].ToString();
答案 1 :(得分:0)
if(chkenbl.IsChecked)
{
insert 1..
}
else
{
insert 0..
}