如果在文本框中写入文本时如何在gridview中选中复选框= true?
这是我正在尝试的代码:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
foreach (GridViewRow row in gvTeacherPage.Rows)
{
CheckBox chbAbsence = (CheckBox)row.FindControl("chbAbsence");
if (connect.checkStudentNo(int.Parse(TextBox1.Text)) == true && TextBox1 .Text != "")
{ chbAbsence.CheckedChanged += new EventHandler(chbAbsence_CheckedChanged);
if (connect.checkStudentNo(int.Parse(TextBox1.Text)) == false && TextBox1.Text == "")
{
chbAbsence.CheckedChanged += new EventHandler(chbAbsence_CheckedChanged);
}
}
ShowAlertMessage("process completed successfully");
ddlCourseName_SelectedIndexChanged(null, null);
TextBox1.Text = string.Empty;
}
// this is checking event
private void chbAbsence_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = sender as CheckBox ;
if (!chk.Checked)
chk.Checked = true;
else
chk.Checked = false;
}
答案 0 :(得分:0)
不幸的是,这不会像你期望的那样发挥作用。
Gridviews(和DataGrids)有复选框和单选按钮的回发问题;你可以将AutoPostBack属性设置为true并处理网格ItemCommand,期望在检查或取消选中网格内的复选框时引发该事件,但由于checkbox和radiobutton控件没有CommandName或CommandArgument属性,它们永远不会触发ItemCommand。
您的方法(动态分配事件处理程序)也不起作用。但是,它可以做到。诀窍是在Page Init / Load中检查表单POST变量'__EVENTTARGET',查找复选框控件的名称。如果此表单变量(ASP.NET生成)包含控件的名称,则它是已选中/未选中的名称。
(当然在GridView或DataGrid中,WebForms会破坏控件的ID,并且可能会有几个;这就是你进行CONTAINS搜索的原因)
以下举例说明;它来自DataGrid,但转换为GridView很简单。
页面加载中的: -
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// do whatever when page first loads
}
else
{
TestForCheckedChanged();
}
}
方法本身: -
private void TestForCheckedChanged()
{
if (Request.Form["__EVENTTARGET"] != null)
{
string target = Request.Form["__EVENTTARGET"];
// check for the name of your control
if (target.Contains("chkSelect"))
{
// got one - do a Page.FindControl on the actual name, which will be
// something like ctl00_row1_chkSelect11 or something similar
var chk = Page.FindControl(target) as CheckBox;
if (chk != null)
{
// from here you can get to the datagrid/view item
var item = chk.BindingContainer as DataGridItem;
// note; my example assumes an integer ID is used as the grid DataKeyField
int key = Convert.ToInt32(grid.DataKeys[item.ItemIndex]);
// from here, can get any other controls in that grid row
var txt = grid.Items[key].FindControl("txtSomething");
// you can also get the value of the checkbox itself; 'on' is checked
if (Request.Form[target] == "on")
{
// do something because checkbox was checked
}
else
{
// do something because checkbox was unchecked
}
}
}
}
}
尝试一下,如果您需要任何帮助,请告诉我。