我有一个gridview,在gridview的一列中我有两个不同ID的复选框 所以我在单击一个按钮(更新按钮)循环行并检查该特定行的复选框是否已选中后执行foreach循环,然后我想在单击按钮后一起更新所有行
我在Page_Load()中填充gridview,foreach循环根据行数进行正确的循环次数,但是在检查复选框是否被选中时它不会进入我的If语句
以下是我的代码:
protected void btnUpdate_Click(object sender, EventArgs e)
{
int count = 0;
foreach (GridViewRow row in GridView1.Rows)
{
count++;
if (((CheckBox)row.FindControl("showBbtn")).Checked & ((CheckBox)row.FindControl("showCbtn")).Checked) // if 2 buttons are checked show error popout
{
Response.Write(@"<script language='javascript'>alert('You can only select Yes or No')</script>");
}
else
{
if (((CheckBox)row.FindControl("showCbtn")).Checked) // Won't enter
{
//Do something here.
}
if (((CheckBox)row.FindControl("showBbtn")).Checked) // Won't enter
{
// Do something here.
}
}
}
Response.Write(count);
}
这就是我填充gridview的方式:
protected void Page_Load(object sender, EventArgs e)
{
BindQuestion(); // Foreach loop count is according to the number of rows
if (!Page.IsPostBack)
{
// BindQuestion(); // Can enter the if loop but the foreach loop count is only 1.
}
}
我的aspx:
<asp:TemplateField HeaderText="Display">
<ItemTemplate>
<asp:CheckBox ID="showCbtn" runat="server" Text = "Yes" />
<br />
<asp:CheckBox ID="showBbtn" runat="server" Text = "No" />
</ItemTemplate>
</asp:TemplateField>
答案 0 :(得分:1)
你的If条件有问题。你给出了错误的&amp;标志,它应该是两个&amp;&amp; sign.Replace
if (((CheckBox)row.FindControl("showBbtn")).Checked & ((CheckBox)row.FindControl("showCbtn")).Checked)
带
if (((CheckBox)row.FindControl("showBbtn")).Checked && ((CheckBox)row.FindControl("showCbtn")).Checked)
并在ispostback中添加BindQuestion()。
答案 1 :(得分:1)
这可能对您有所帮助
foreach (GridViewRow gr in grdCreateDues.Rows)
{
CheckBox chkC = gr.FindControl("showCbtn") as CheckBox;
CheckBox chkB = gr.FindControl("showBbtn") as CheckBox;
GridViewRow Row = ((GridViewRow)chk.Parent.Parent);
if (chkC.Checked)
{
// update tblGridtable set xzy = @xyz
}
else if (chk.B.Checked)
{
// update tblGridtable set abc = @abc
}
}
答案 2 :(得分:0)
尝试使用: -
CheckBox chbx = GridView1.HeaderRow.FindControl("CheckBox1") as CheckBox;
if (chbx != null && chbx.Checked)
{
Condition
}
答案 3 :(得分:0)
此方法也有效
var checkBox = (CheckBox)item.FindControl("ckbActive");