如何在asp.net的GridView中按列名获取单元格值而不是索引

时间:2012-03-15 08:14:18

标签: asp.net gridview

我在asp.net中有gridview,现在我希望列名的单元格值,而不是单元索引。

如何通过单元格列名

检索单元格值

10 个答案:

答案 0 :(得分:66)

GridView不会充当列名,因为知道这些内容的是datasource属性。

如果您仍然需要知道给定列名的索引,那么您可以创建一个帮助方法来执行此操作,因为gridview标头通常包含此信息。

int GetColumnIndexByName(GridViewRow row, string columnName)
{
    int columnIndex = 0;
    foreach (DataControlFieldCell cell in row.Cells)
    {
        if (cell.ContainingField is BoundField)
            if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
                break;
        columnIndex++; // keep adding 1 while we don't have the correct name
    }
    return columnIndex;
}

请记住上面的代码将使用BoundField ...然后使用它:

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int index = GetColumnIndexByName(e.Row, "myDataField");
        string columnValue = e.Row.Cells[index].Text;
    }
}

我强烈建议您使用TemplateField拥有自己的控件,然后更容易抓住这些控件:

<asp:GridView ID="gv" runat="server">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

然后使用

string columnValue = ((Label)e.Row.FindControl("lblName")).Text;

答案 1 :(得分:2)

虽然很长一段时间,但这段相对较小的代码似乎很容易阅读并得到:

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
   int index;
   string cellContent;

    foreach (TableCell tc in ((GridView)sender).HeaderRow.Cells)
    {
       if( tc.Text.Equals("yourColumnName") )
       {
         index = ((GridView)sender).HeaderRow.Cells.GetCellIndex(tc);
         cellContent = ((GridView)sender).SelectedRow.Cells[index].Text;
         break;
       }
    }
}

答案 2 :(得分:2)

您可以使用DataRowView获取列索引。

    void OnRequestsGridRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var data = e.Row.DataItem as DataRowView;

            // replace request name with a link
            if (data.DataView.Table.Columns["Request Name"] != null)
            {
                // get the request name
                string title = data["Request Name"].ToString();
                // get the column index
                int idx = data.Row.Table.Columns["Request Name"].Ordinal;

                // ...

                e.Row.Cells[idx].Controls.Clear();
                e.Row.Cells[idx].Controls.Add(link);
            }
        }
    }

答案 3 :(得分:2)

对于Lambda爱好者

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var boundFields = e.Row.Cells.Cast<DataControlFieldCell>()
            .Select(cell => cell.ContainingField).Cast<BoundField>().ToList();

        int idx = boundFields.IndexOf(
            boundFields.FirstOrDefault(f => f.DataField == "ColName"));

        e.Row.Cells[idx].Text = modification;        
    }
}

答案 4 :(得分:0)

亚历山大答案中索引列的一个小错误: 我们需要照顾&#34;未找到&#34;柱:

int GetColumnIndexByName(GridViewRow row, string columnName)
{
    int columnIndex = 0;
    int foundIndex=-1;
    foreach (DataControlFieldCell cell in row.Cells)
    {
        if (cell.ContainingField is BoundField)
        {
            if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
            {
                foundIndex=columnIndex;
                break;
            }
        }
        columnIndex++; // keep adding 1 while we don't have the correct name
    }
    return foundIndex;
}

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int index = GetColumnIndexByName(e.Row, "myDataField");
        if( index>0)
        {
            string columnValue = e.Row.Cells[index].Text;
        }
    }
}

答案 5 :(得分:0)

基于Code Project

上找到的内容

根据网格的数据源声明数据表后,从列集合中按列名查找列索引。此时,根据需要使用索引从单元格获取信息或格式化单元格。

protected void gridMyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataTable dt = (DataTable)((GridView)sender).DataSource;
        int colIndex = dt.Columns["MyColumnName"].Ordinal;

        e.Row.Cells[colIndex].BackColor = Color.FromName("#ffeb9c");
    }
}

答案 6 :(得分:0)

标题行单元格有时不起作用。这将只返回列索引。它将以很多不同的方式提供帮助。我知道这不是他要求的答案。但这对很多人都有帮助。

public static int GetColumnIndexByName(GridView gridView, string columnName)
    {      
        for (int i = 0; i < gridView.Columns.Count ; i++)
        {
            if (gridView.Columns[i].HeaderText.ToUpper() == columnName.ToUpper() )
            {
                return i;
            }
        }     
        return -1;
    }

答案 7 :(得分:0)

//get the value of a gridview
public string getUpdatingGridviewValue(GridView gridviewEntry, string fieldEntry)
    {//start getGridviewValue
        //scan gridview for cell value
            string result = Convert.ToString(functionsOther.getCurrentTime()); 
            for(int i = 0; i < gridviewEntry.HeaderRow.Cells.Count; i++)
                {//start i for
                    if(gridviewEntry.HeaderRow.Cells[i].Text == fieldEntry)
                        {//start check field match
                            result = gridviewEntry.Rows[rowUpdateIndex].Cells[i].Text;
                            break;
                        }//end check field match
                }//end i for
        //return
            return result;
    }//end getGridviewValue

答案 8 :(得分:0)

可以很容易地使用数据字段名称(如果不是标题),这为我解决了问题。对于ASP.NET和VB:

例如对于字符串:

Dim编码= e.Row.DataItem(“ Encoding”)。ToString()。Trim()

例如对于整数:

Dim MsgParts = Convert.ToInt32(e.Row.DataItem(“ CalculatedMessageParts”)。ToString())

答案 9 :(得分:0)

protected void CheckedRecords(object sender, EventArgs e)

    {
       string email = string.Empty;
        foreach (GridViewRow gridrows in GridView1.Rows)

        {

            CheckBox chkbox = (CheckBox)gridrows.FindControl("ChkRecords");
    if (chkbox != null & chkbox.Checked)

            {

    int columnIndex = 0;
                foreach (DataControlFieldCell cell in gridrows.Cells)
                {
                    if (cell.ContainingField is BoundField)
                        if (((BoundField)cell.ContainingField).DataField.Equals("UserEmail"))
                            break;
                    columnIndex++; 
                }


                email += gridrows.Cells[columnIndex].Text + ',';
                  }

        }

        Label1.Text = "email:" + email;

    }