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

Posted

技术标签:

【中文标题】如何在asp.net的GridView中按列名而不是按索引获取单元格值【英文标题】:How to get the cell value by column name not by index in GridView in asp.net 【发布时间】:2012-03-31 17:45:21 【问题描述】:

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

如何通过单元格列名检索单元格值

【问题讨论】:

你什么时候想要那个值?在网格呈现到页面之前还是在提交之后? 【参考方案1】:

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;

【讨论】:

同意。救生员。谢谢!这是在我的“实用小袋子”中 @balexandre 如果它是一个 TemplateField 怎么办?我连续拥有 BoundField 和 TemplateField。 你甚至可以使用 Linq 来查找单元格: var targetCell = from DataControlFieldCell cell in row.Cells where ((BoundField)cell.ContainingField).DataField == fieldName select cell; 函数返回cells.Count,如果没有找到名字【参考方案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;
       
    

【讨论】:

【参考方案3】:

您可以使用 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);
            
        
    

【讨论】:

【参考方案4】:

对于 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;        
    

【讨论】:

【参考方案5】:

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

public static int GetColumnIndexByHeaderText(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;
    

【讨论】:

【参考方案6】:

基于在 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");
    

【讨论】:

请不要只发布纯代码。继续解释你的解决方案。 GridView 的DataSource 是DataSet,而不是DataTable。您可能会遇到转换错误。【参考方案7】:

亚历山大的回答中 indexcolumn 的一个小错误: 我们需要处理“未找到”列:

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;
        
    

【讨论】:

【参考方案8】:
//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

【讨论】:

【参考方案9】:

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

例如对于字符串:

Dim Encoding = e.Row.DataItem("Encoding").ToString().Trim()

例如对于整数:

Dim MsgParts = Convert.ToInt32(e.Row.DataItem("CalculatedMessageParts").ToString())

【讨论】:

【参考方案10】:
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;

                               

【讨论】:

除了提供代码外,您还应该解释为什么代码有效。在 Stack Overflow 上总是建议这样做,但对于具有公认答案的旧问题,它尤其很重要。你为什么采取与接受的答案不同的方法?在什么情况下有人会更喜欢你的方法?你介意用这些信息编辑你的答案吗?这将使它对社区更有用,尤其是对新开发者。

以上是关于如何在asp.net的GridView中按列名而不是按索引获取单元格值的主要内容,如果未能解决你的问题,请参考以下文章

ASP.net 自定义 GridView 控件

asp.net VS2008 GridView 里面怎么排序

如何使用 C# 在 gridview 中添加新行?

从 ftp 在 gridview 上显示数据 查看更多:C#ASP.NET

如何在 c# ASP.NET 中使用 GridView_RowCommand 事件从 GridView 获取图像

如何在编辑模式 ASP .Net 中将日期选择器放在 Gridview 中