[英]Link button to display grid view asp.net dynamically
我必須顯示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++;
}
提前致謝。
如下修改您的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事件中添加所有動態添加的控件,以維持其狀態。 請參考以下鏈接。
從Page_Init
事件中調用方法GenerateControls
,如下所示。
protected void Page_Init(object sender, EventArgs e)
{
GenerateControls();
}
編輯:
JavaScript函數...
function ShowGrid(gridID) {
document.getElementById(gridID).style.display = ''
}
我將服務器端單擊事件保持原樣。 但是我評論了事件處理程序分配給鏈接按鈕的那一行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.