[英]Append GridView-Columns after DataTable was databound
我有一个我在代码文件中创建的DataTable
,后来我将它绑定到我使用Visual Studio的拖放功能创建的GridView
。
但是我在GridView
添加了一些列,这些列在DataTable
不受支持(如果我错了,请更正我),例如Hyperlink-Column或CheckBox-Column。
我想构建超链接列和复选框id,其中的值是从特定列的DataTable
生成的值派生的。 我知道我可以使用DataNavigateUrlfields
来构建动态链接,但是如何使用稍后要绑定的DataTable
呢?
我还需要GridView
中的列出现在DataTable
的列之后。
任何有关上述帮助将受到高度赞赏。 任何替代方案也值得赞赏。
将首先创建声明性添加的控件,然后创建数据绑定/手动创建(在页面的生命周期中记录 , “声明性地创建控件” )。 由于您希望声明性列最后,您需要一个hack:
您可以使用RowDataBound
来更改顺序,以便AutoGenerated
列跟随您的其他列,如Hyperlink
或CheckBox
列:
protected void gridOffers_RowDataBound(object sender, GridViewRowEventArgs e)
{
TableCell cell = e.Row.Cells[0];
e.Row.Cells.RemoveAt(0);
//Move first to the end
e.Row.Cells.Add(cell);
cell = e.Row.Cells[0];
e.Row.Cells.RemoveAt(0);
//Move second to the end
e.Row.Cells.Add(cell);
}
但是我在GridView中添加了一些列,这些列在DataTable中不受支持(如果我错了,请更正我),例如Hyperlink-Column或CheckBox-Column。
它们不需要在DataTable中支持,而是在GridView中支持。 该表包含您的数据,网格包含视图。
您可以尝试使用此代码 - 基于RowDataBound
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" Text=""></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
您可以使用事件RowDataBound调整datbound,我添加了HyperLink控件,以便根据需要自定义链接。
void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var hyperLink = (HyperLink)e.Item.FindControl("HyperLink1");
hyperLink.NavigateUrl ="....";
var checkBox = (CheckBox)e.Item.FindControl("CheckBox1");
checkBox.Checked =....
}
}
如果您正在使用数据表,那么有一种简单的方法可以附加列
DataTable yourDataTable = new DataTable();
Load yourDataTable by DataReader or DataAdapter
DataColumn newColumn = yourDataTable.Columns.Add("Total", typeof(Int32));
之后,您可以将此数据表绑定到Gridview中。 MSDN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.