当选中的复选框数等于3时,我尝试在GridView中启用该按钮。
我使用过这段代码,但GridView中的按钮总是被禁用,为什么?
你能帮助我吗?
感谢您的关注。
int count;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
if (count == 3)
{
btn.Enabled = true;
}
else
{
btn.Enabled = false;
}
}
}
protected void btn_Click(object sender, EventArgs e)
{
string strname = string.Empty;
string strnamesplit = string.Empty;
count = 0;
foreach (GridViewRow gvrow in GridView1.Rows)
{
HiddenField hiddenField = (HiddenField)gvrow.FindControl("HiddenField1");
CheckBox chk = (CheckBox)gvrow.FindControl("cb");
if (chk != null & chk.Checked)
{
strname += hiddenField.Value + ',';
count++;
}
}
strname = strname.Trim(",".ToCharArray());
Response.Write("Selected UserNames: <b>" + strname + "</b><br /><br />");
string[] words = strname.Split(',');
foreach (string word in words)
{
Response.Write(word + "<br />");
}
Response.Write(count.ToString() + "<br />");
}
<asp:CheckBox ID="cb" runat="server" AutoPostBack="true" />
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%#Eval("id")%>' />
<asp:Button runat="server" ID="btn" Text="Enviar" OnClick="btn_Click" Enabled="false" />
答案 0 :(得分:0)
因为PageLoad在btn_Click之前触发。我建议您将代码事件更改为 Page_PreRender :
protected void Page_PreRender(object sender, EventArgs e)
{
if (count == 3)
{
btn.Enabled = true;
}
else
{
btn.Enabled = false;
}
}
答案 1 :(得分:0)
您应该使用OnCheckedChanged事件。
修改您的aspx页面:
<asp:CheckBox ID="cb" runat="server" AutoPostBack="true"
OnCheckedChanged="CheckBox1_CheckedChanged" />
修改您的代码:
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkTest = (CheckBox)sender;
GridViewRow grdRow = (GridViewRow)chkTest.NamingContainer;
count = 0;
foreach (GridViewRow gvrow in GridView1.Rows)
{
CheckBox chk = (CheckBox)gvrow.FindControl("cb");
if (chk.Checked)
{
count++;
}
}
if (count == 3)
{
btn.Enabled = true;
}
else
{
btn.Enabled = false;
}
Response.Write(count.ToString() + "<br />");
}
protected void btn_Click(object sender, EventArgs e)
{
string strname = string.Empty;
foreach (GridViewRow gvrow in GridView1.Rows)
{
HiddenField hiddenField = (HiddenField)gvrow.FindControl("HiddenField1");
CheckBox chk2 = (CheckBox)gvrow.FindControl("cb");
if (chk2 != null & chk2.Checked)
{
strname += hiddenField.Value + ",";
strname = strname.Trim(",".ToCharArray());
Response.Write("Selected UserNames: <b>" + strname.ToString() + "</b><br />");
string[] words = strname.Split(',');
foreach (string word in words)
{
Response.Write(word.ToString() + "<br /><br />");
}
}
}
}