如何获取列名并动态创建字符串变量?

时间:2016-10-08 11:48:23

标签: c# gridview

通过编辑链接按钮,我可以使用下面的代码编辑记录。正如您在这里看到的列数是4,对于固定列号,此代码很好,但在我的条件下,列号不固定,它们可能为4或下一次插入可能为5。如何获取列名并创建该字符串变量数,以便我可以将字符串值分配给特定字段?

  protected void OnUpdate(object sender, EventArgs e)
{
    GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;

    string a = (row.Cells[3].Controls[0] as TextBox).Text;
    string b = (row.Cells[4].Controls[0] as TextBox).Text;
    string c = (row.Cells[5].Controls[0] as TextBox).Text;
    string d = (row.Cells[6].Controls[0] as TextBox).Text;

    DataTable dt = ViewState["dt"] as DataTable;

    dt.Rows[row.RowIndex]["Column0"] = a;
    dt.Rows[row.RowIndex]["Column1"] = b;
    dt.Rows[row.RowIndex]["Column2"] = c;
    dt.Rows[row.RowIndex]["Column3"] = d;

    ViewState["dt"] = dt;
    GridView1.EditIndex = -1;
    this.BindGrid();
    btnGetSelected.Visible = true;

}

2 个答案:

答案 0 :(得分:1)

您的意思是需要GridView的列名吗?

您可以使用其中任何一种

gv.HeaderRow.Cells[i].Text

gv.Rows[0].Cells[i].Text

Reference

您希望DataTable使用

列名称
string[] columnNames = dt.Columns.Cast<DataColumn>()
                                 .Select(x => x.ColumnName)
                                 .ToArray();  

答案 1 :(得分:1)

这对我有用。

 protected void OnUpdate(object sender, EventArgs e)
{
    GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
    DataTable dt = ViewState["dt"] as DataTable;
    int j=0;
    for (int i = 3; i < row.Cells.Count; i++)
    {
          string a = (row.Cells[i].Controls[0] as TextBox).Text;
          dt.Rows[row.RowIndex][j] = a;
          j++;
    }
    ViewState["dt"] = dt;
    GridView1.EditIndex = -1;
    this.BindGrid();
    btnGetSelected.Visible = true;
}