读书人

怎么读取DataGridView中的DataGridVie

发布时间: 2012-02-05 12:07:15 作者: rapoo

如何读取DataGridView中的DataGridViewColumn当前选定项的显示值—isplayMember)
对于DataGridView中的DataGridViewColumn,绑定了DisplayMember、ValueMember之后,如何从程序中读取DisplayMember对应项的内容?

DataTable dt = new DataTable();
dt.Columns.Add( "Value ", typeof(int));
dt.Columns.Add( "Display ", typeof(string));

dt.Rows.Add( 1, " " );
dt.Rows.Add( 2, "外 " );

gridColumn.DisplayMember = "Display ";
gridColumn.ValueMember = "Value ";
gridColumn.DataSource = dt;

grid.Rows[0].Cells[gridColumn.Name].Value = 2;
//读取
int value=grid.Rows[0].Cells[gridColumn.Name].Value;//可以读取value值
string display=??? //如何读取当前的显示内容?



[解决办法]
string display=dataGridView1.Rows[0].Cells[0].Tag.tostring()
[解决办法]
如果DATAGRID的数据源是DATATABLE,可使用string display=datatable对象.Rows[索引][索引].ToString();获得
[解决办法]
请参考:

string courseNumber = (string)this.dataGridCourses[this.dataGridCourses.CurrentRowIndex, 0];
Course selectedCourse = (Course)courses[this.dataGridCourses.CurrentRowIndex];

//Course 是个实体类型
[解决办法]
DataGridView1.CurrentRow.Cells[ "Description "].FormattedValue;
[解决办法]
楼主可以在添加每一列时,取一个列名,如下所示,
this.DataGridView1.Columns.Add( "Number ", "编号 ");
this.DataGridView1.Columns.Add( "Id ", "序号 ");
然后要取值时就可以用以下方法来取值了:
this.DataGridView1.Rows[rowIndex].Cells[ "Number "].Value.ToString();
this.DataGridView1.Rows[rowIndex].Cells[ "Id "].Value.ToString();

读书人网 >C#

热点推荐