如何在列出的gridview事件之一中将IBM的值更改为像思科那样的任意值?
动态网格视图中可能存在不同的列,因此可以按名称对列进行寻址。
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable("TestTable");
dt.Columns.AddRange(new DataColumn[] { new DataColumn("id"), new DataColumn("customername") });
DataRow dr = dt.NewRow();
dr[0] = "1";
dr[1] = "Microsoft";
dt.Rows.Add(dr);
DataRow dr2 = dt.NewRow();
dr2[0] = "2";
dr2[1] = "IBM";
dt.Rows.Add(dr2);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_DataBinding(object sender, EventArgs e)
{
}
protected void GridView1_DataBound(object sender, EventArgs e)
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
}
}
}
答案 0 :(得分:2)
当AutogenerateColumns设置为true
时(默认),此操作无效。您需要以编程方式或声明方式添加列(在aspx标记中)。然后,您可以使用TemplateField和Label
之类的控件,您可以在代码隐藏中引用它:
例如:
<asp:GridView ID="GridView1" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound" runat="server">
<Columns>
<asp:TemplateField HeaderText="Customer">
<ItemTemplate>
<asp:Label ID="LblCustomer" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
RowDataBound非常完美(适用于几乎所有事情):
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow) {
var row = ((DataRowView)e.Row.DataItem).Row;
var lblCustomer = (Label)e.Row.FindControl("LblCustomer");
var customerName = row.Field<String>( "customername" );
if(customerName == "Microsoft") {
customerName = "Cisco";
}
lblCustomer.Text = customerName;
}
}
修改:好的,永远不需要这样做。但实际上即使将AutoGenerateColumns
设置为true
,您也可以将 Microsoft 值更改为 Cisco 。
GridView
数据绑定之前触发了DataBinding事件。如果在数据源绑定到网格之前更改数据源,则可以对其进行修改:
protected void GridView1_DataBinding(object sender, EventArgs e)
{
var tbl = (DataTable)((GridView)sender).DataSource;
var msRows = tbl.AsEnumerable()
.Where(r => r.Field<String>("customername") == "Microsoft")
.Select(r => r);
foreach(DataRow msRow in msRows) {
msRow[ "customername" ] = "Cisco";
}
}
注意:当然你也可以使用一个简单的循环而不是LINQ