如何读取特定列中的所有行并在网格视图asp.net中绑定之前进行更改

在我的例子中,我private static readonly Dictionary<byte, string>在一个结构内部定义了一个来保存预定义的常量。这通常可以正常工作,但是我还在我的结构中定义了一个 MinValue 来表示一条数据的最小值。以这种方式完成时,静态字典未初始化,除非在静态 MinValue 属性上方定义。我可能对编译器的要求太多了,应该对其进行重构。


在大型结构中很难诊断,因为我没想到 C# 会出现这种行为。重现示例:


public struct MyStruct

{

    public string Str;


    public static readonly MyStruct MinValue = new MyStruct(0);


    public MyStruct(byte val)

    {

        Str = _predefinedValues[val]; // null reference exception

    }


    private static readonly Dictionary<byte, string> _predefinedValues = new Dictionary<byte, string>()

    {

        {0x00, "test 1"},

        {0x01, "test 2"},

        {0x02, "test 3"},

    };


}


婷婷同学_
浏览 100回答 2
2回答

守候你守候我

由于ds.Tables[0]包含DataTable对象,您可以使用DataRow.Field<T>()扩展方法从指定的列名中查找值,将值替换为SetField()然后重新绑定对网格数据源的更改:foreach (DataRow dr in ds.Tables[0].Rows){&nbsp; &nbsp; string oldValue = dr.Field<string>("ColumnName");&nbsp; &nbsp; // check if the column has value&nbsp; &nbsp; if (!string.IsNullOrEmpty(oldValue))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; dr.SetField("ColumnName", value.ToString());&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // do something else&nbsp; &nbsp; }}ds.Tables[0].AcceptChanges();// rebind the data source here请注意,DataRow.Field<T>将值转换为由Ttype 参数指定的类型,因此以下 if 条件使用 check againstnull或空字符串而不是DBNull.Value.

慕妹3146593

首先,bind您的grid view并添加OnRowDataBound喜欢<asp:GridView ID="GridView1" runat="server" OnRowDataBound = "OnRowDataBound">RowDataBound事件是triggered for each GridView RowRowGridView绑定到数据的时间。然后在您的OnRowDataBound事件代码中protected void OnRowDataBound(object sender, GridViewRowEventArgs e){&nbsp; &nbsp; if (e.Row.RowType == DataControlRowType.DataRow)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; column1 = e.Row.Cells[1].Text;&nbsp; &nbsp; &nbsp; &nbsp; //here you can give the column no that you want get like e.Row.Cells[1]&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; e.Row.Cells[1].Text="test";&nbsp; &nbsp; &nbsp; &nbsp;//you can set what you want like this&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP