我正在创建一个带有动态控件的GridView(包括itemtemplates)。 这是html代码。
<asp:GridView ID="gvItems" runat="server"
AutoGenerateColumns="False" CellPadding="4"
GridLines="None"
Width="95%" EmptyDataText="Records Not Found!!!!"
onselectedindexchanged="gvItems_SelectedIndexChanged"
onrowdatabound="gvItems_RowDataBound" onrowcommand="gvItems_RowCommand"
onselectedindexchanging="gvItems_SelectedIndexChanging">
<RowStyle CssClass="GVRowStyle" />
<Columns>
</Columns>
<PagerStyle CssClass="gridPager" />
<SelectedRowStyle BackColor="#DCCDDA" Font-Bold="true" ForeColor="#510030" />
<HeaderStyle CssClass="Gheader" />
<AlternatingRowStyle CssClass="AlternatingRowStyle" />
<EditRowStyle BackColor="#7C6F57" />
<EmptyDataRowStyle CssClass="EmptyRowStyle" />
</asp:GridView>
这是Add ItemTemplate的类...................................
public class GridViewTemplate : ITemplate
{
ListItemType _templateType;
string _columnName;
public GridViewTemplate(ListItemType type, string colname)
{
_templateType = type;
_columnName = colname;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_templateType)
{
case ListItemType.Header:
Label lbl = new Label();
lbl.Text = _columnName;
container.Controls.Add(lbl);
break;
case ListItemType.Item:
LinkButton Lb1 = new LinkButton();
Lb1.CommandName = "Select";
Lb1.DataBinding += new EventHandler(tb1_DataBinding);
container.Controls.Add(Lb1);
break;
case ListItemType.EditItem:
break;
case ListItemType.Footer:
CheckBox chkColumn = new CheckBox();
chkColumn.ID = "Chk" + _columnName;
container.Controls.Add(chkColumn);
break;
}
}
void tb1_DataBinding(object sender, EventArgs e)
{
LinkButton LinkData = (LinkButton)sender;
GridViewRow container = (GridViewRow)LinkData.NamingContainer;
object dataValue = DataBinder.Eval(container.DataItem, _columnName);
if (dataValue != DBNull.Value)
{
LinkData.Text = dataValue.ToString();
LinkData.ForeColor = System.Drawing.Color.Red;
LinkData.CommandName = "Select";
}
}
}
这是页码......................................... < / p>
for (int i = 0; i < dtGrid.Columns.Count; i++)
{
string columnName = dtGrid.Columns[i].ColumnName;
BoundField bField = new BoundField();
TemplateField tField = new TemplateField();
if (i == 0)
{
tField.HeaderTemplate = new GridViewTemplate(ListItemType.Header, columnName);
tField.ItemTemplate = new GridViewTemplate(ListItemType.Item, columnName);
tField.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
tField.ItemStyle.ForeColor = System.Drawing.Color.Red;
gvItems.Columns.Add(tField);
}
else
{
bField.DataField = columnName;
bField.HeaderText = columnName;
bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
gvItems.Columns.Add(bField);
}
现在问题是,当我点击链接按钮时,它会消失,除了rowdatabound之外没有任何事件被引发。
答案 0 :(得分:2)
由于您是动态创建这些列,因此您需要在每次回发时重新创建控件。对于未触发的事件处理程序,请确保在页面生命周期中尽早创建列。我建议创建动态列OnInit
,看看是否能解决问题。
答案 1 :(得分:-1)
您是否重新绑定了回发数据? 请确保数据绑定逻辑包含if(!IsPostback) 网格的重新绑定意味着重新创建按钮,因此不会触发任何事件。