在我的页面中,我从代码中填充 GridView ,方法是将源代码设置为我从XML文件编译的自定义数据表,这样我就可以编写列标题和行标题。 这工作正常,所以我在单元格中添加复选框,同时以这种方式添加列:
DataTable dt = new DataTable();
dt.Columns.Add(" ");
foreach (XmlNode xns in doc.DocumentElement.ChildNodes[0])
{
foreach (XmlNode xn in xns)
{
string tagName = xn.Name;
dt.Rows.Add(tagName);
}
}
dt.Columns.Add("Mattina Turno 1", typeof(bool)); //this adds the checkbox
dt.Columns.Add("Mattina Turno 2", typeof(bool));
dt.Columns.Add("Pomeriggio", typeof(bool));
GridView1.DataSource = dt;
GridView1.DataBind();
我以这种方式启用Gridview RowDataBound中的每个复选框,其中 GridViewRowEventArgs 为e:
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
for (int i = 0; i < e.Row.Cells.Count;i++)
{
if (e.Row.Cells[i].GetType() == typeof(System.Web.UI.WebControls.DataControlFieldCell))
{
TableCell tc = e.Row.Cells[i];
if (tc.Controls.Count > 0)
{
CheckBox cb = (CheckBox)tc.Controls[0];
if (cb != null)
{
cb.Enabled = true;
colonna = ((GridView)sender).HeaderRow.Cells[i].Text;
riga = e.Row.Cells[0].Text;
cb.CausesValidation = false;
cb.ID = riga + " " + colonna;
cb.ToolTip = riga + " " + colonna;
cb.AutoPostBack = true;
cb.CheckedChanged += new EventHandler(Cb_CheckedChanged);
cb.Attributes.Add("runat", "server");
}
}
}
}
}
但是当我尝试处理复选框的检查事件时,没有任何反应。 checkchanged应该调用 Cb_CheckedChanged ,但没有任何反应。
这是Cb_CheckChanged:
private void Cb_CheckedChanged(object sender, EventArgs e)
{
Cliccato.Text = ((CheckBox)sender).ID.ToString();
System.Diagnostics.Debug.Write(((CheckBox)sender).ToolTip);
}
autopostback似乎有效,因为当我单击一个复选框时页面刷新但它不处理任何事件... 请帮助我,我真的需要你的帮助!
答案 0 :(得分:0)
您没有在代码中设置runat服务器属性,因此选中/取消选中复选框时没有任何操作。
也许你可以尝试这样的事情:
cb.Attributes.Add("runat", "server");
您还应在if块中放置一个断点,并检查代码是否进入控件初始化部分。
答案 1 :(得分:0)
将CheckBox动态添加到GridView,如:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
// check if it's not a header and footer
if (e.Row.RowType == DataControlRowType.Row)
{
CheckBox chk = new CheckBox();
chk.AutoPostBack = true;
// add checked changed event to checkboxes
chk.CheckedChanged += new EventHandler(chk_CheckedChanged);
e.Row.Cells[1].Controls.Add(chk); // add checkbox to second column
}
}
要从每行的单元格中获取文本,请使用RowDataBound
中的代码:
if (e.Row.RowType == DataControlRowType.Row)
{
// assuming there is label in first cell, you cast it that you want
string cellText = (e.Row.Cells[0].FindControls("Label1") as Label).Text;
}