我有我的datagridview,我想将这些信息传递到数据表或其他地方,我正在尝试这个
Dim dt As DataTable
dt = CType(DataGridView1.DataSource, DataTable)
但我只是空了,有什么想法吗?我不知道如何从datagridview获取信息
答案 0 :(得分:0)
你可以试试这个。
dt = TryCast(DataGridView1.DataSource, DataTable)
或
Dim dt As New DataTable
dt = (DirectCast(DataGridView1.DataSource, DataTable))
或者
使用以下函数从Grid获取Datatable
public DataTable DataGridView2DataTable(DataGridView dgv, String tblName, int minRow=0){
DataTable dt = new DataTable(tblName);
// Header columns
foreach (DataGridViewColumn column in dgv.Columns)
{
DataColumn dc = new DataColumn(column.Name.ToString());
dt.Columns.Add(dc);
}
// Data cells
for (int i = 0; i < dgv.Rows.Count; i++)
{
DataGridViewRow row = dgv.Rows[i];
DataRow dr = dt.NewRow();
for (int j = 0; j < dgv.Columns.Count; j++)
{
dr[j] = (row.Cells[j].Value == null) ? "" : row.Cells[j].Value.ToString();
}
dt.Rows.Add(dr);
}
// Related to the bug arround min size when using ExcelLibrary for export
for (int i = dgv.Rows.Count; i < minRow; i++)
{
DataRow dr = dt.NewRow();
for (int j = 0; j < dt.Columns.Count; j++)
{
dr[j] = " ";
}
dt.Rows.Add(dr);
}
return dt;
}
答案 1 :(得分:0)
我有一个解决方案,它有点脏,但......它适用于我
Dim valor As Integer
valor = DataGridView1.RowCount
valor = valor - 2
For indice As Integer = 0 To valor
' DataGridView1.Item(0, indice).Value.ToString()
' DataGridView1.Item(1, indice).Value.ToString()
' in my case i only have two colums but if tyou have more you can use double for
Next
希望这能帮助别人:)