我必须显示n
网格,n
是可变的,然后我不知道我会有多少个网格。
我的问题是,我必须使用Visible false初始化此网格,当单击按钮显示该按钮的特定网格时,如何将按钮链接到gridview?
生成网格的代码:
foreach (List<DataRow> lst in grids)
{
dt = lst.CopyToDataTable();
GridView grv = new GridView();
grv.AlternatingRowStyle.BackColor = System.Drawing.Color.FromName("#cccccc");
grv.HeaderStyle.BackColor = System.Drawing.Color.Gray;
grv.ID = "grid_view"+i;
grv.Visible = false;
grv.DataSource = dt;
grv.DataBind();
Label lblBlankLines = new Label();
lblBlankLines.Text = "<br /><br />";
Label lblTipo = new Label();
string tipoOcorrencia = lst[0]["DESC_OCORRENCIA"].ToString();
tipoOcorrencia = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(tipoOcorrencia);
int quantidade = lst.Count;
lblTipo.Text = tipoOcorrencia + ": " + quantidade;
LinkButton lkBtn = new LinkButton();
lkBtn.ID = "link_button"+i;
lkBtn.Text = "+";
place_grids.Controls.Add(lblBlankLines);
place_grids.Controls.Add(lkBtn);
place_grids.Controls.Add(lblTipo);
place_grids.Controls.Add(grv);
place_grids.DataBind();
i++;
}
提前致谢。
答案 0 :(得分:3)
修改你的foreach循环,如下所示。
private void GenerateControls()
{
int i = 0;
foreach (List<DataRow> lst in grids)
{
dt = lst.CopyToDataTable();
GridView grv = new GridView();
grv.AlternatingRowStyle.BackColor = System.Drawing.Color.FromName("#cccccc");
grv.HeaderStyle.BackColor = System.Drawing.Color.Gray;
grv.ID = "grid_view" + i;
//grv.Visible = false;//Commented as the grid needs be generated on client side, in order to make it visible from JavaScript/jQuery
grv.Attributes.Add("style", "display:none;");
grv.DataSource = dt;
grv.DataBind();
//Adding dynamic link button
LinkButton lnkButton = new LinkButton();
lnkButton.Text = "button " + i;
//lnkButton.Click += new EventHandler(lnkButton_Click);
lnkButton.ID = "lnkButton" + i;
lnkButton.OnClientClick = "ShowGrid('" + grv.ClientID + "');";
Label lblTipo = new Label();
lblTipo.Text = "text " + i;
lblTipo.ID = "lbl" + i;
tempPanel.Controls.Add(lblTipo);
tempPanel.Controls.Add(grv);
tempPanel.Controls.Add(lnkButton);
tempPanel.DataBind();
i++;
}
}
如果您希望触发服务器端事件,则必须按如下所示添加链接按钮单击事件。 (取消注释将事件处理程序分配给链接按钮的行。)
protected void lnkButton_Click(Object sender, EventArgs e)
{
LinkButton lnkButton = (LinkButton)sender;
String index = lnkButton.ID.Substring(lnkButton.ID.Length - 1);
GridView grv = (GridView)tempPanel.FindControl("grid_view" + index);
grv.Visible = true;
}
您需要在Page_Init事件中添加所有动态添加的控件以维护其状态。请参阅下面的链接可能很有用。
Dynamically Created Controls losing data after postback
从GenerateControls
事件中调用方法Page_Init
,如下所示。
protected void Page_Init(object sender, EventArgs e)
{
GenerateControls();
}
编辑:
JavaScript函数......
function ShowGrid(gridID) {
document.getElementById(gridID).style.display = ''
}
我保持服务器端点击事件不变。但我已经注释了将事件处理程序分配给链接按钮的行。