Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

c# - How to get cell value of DataGridView by column name?

I have a WinForms application with a DataGridView, which DataSource is a DataTable (filled from SQL Server) which has a column of xxx. The following code raises the exception of

ArgumentException was unhandled. Column named xxx cannot be found.

foreach (DataGridViewRow row in Rows)
{
    if (object.Equals(row.Cells["xxx"].Value, 123))
}

Is it possible to get the cell values by column name?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

DataGridViewColumn objects have a Name (shown only in the forms designer) and a HeaderText (shown in the GUI at the top of the column) property. The indexer in your example uses the column's Name property, so since you say that isn't working I assume you're really trying to use the column's header.

There isn't anything built in that does what you want, but it's easy enough to add. I'd use an extension method to make it easy to use:

public static class DataGridHelper
{
    public static object GetCellValueFromColumnHeader(this DataGridViewCellCollection CellCollection, string HeaderText)
    {
        return CellCollection.Cast<DataGridViewCell>().First(c => c.OwningColumn.HeaderText == HeaderText).Value;            
    }
}

And then in your code:

foreach (DataGridViewRow row in Rows)
{
    if (object.Equals(row.Cells.GetCellValueFromColumnHeader("xxx"), 123))
    {
        // ...
    }
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...