[英]how to read datagridview data in windows forms coulmn wise in c#
嗨,有人可以建议如何在具有两列(FileName和FilePath)的Windowsforms应用程序中从datagrid读取数据。
下面是我尝试在单列(FileName)中返回所有Filename和FilePath的代码。
任何建议对我都会有帮助。
`
public System.Data.DataTable ExportToExcel()
{
System.Data.DataTable table = new System.Data.DataTable();
table.Columns.Add("FileName", typeof(string));
table.Columns.Add("FilePath", typeof(string));
for (int rows = 0; rows < dataGridView1.Rows.Count; rows++)
{
for (int col= 0; col < dataGridView1.Rows[rows].Cells.Count; col++)
{
table.Rows.Add(dataGridView1.Rows[rows].Cells[col].Value.ToString());
}
}
问题是生产线…
table.Rows.Add(dataGridView1.Rows[rows].Cells[col].Value.ToString());
仅添加到FIRST列。 您正在为EACH列添加新行。
要向具有两列的表中添加一行,格式为:
table.Rows.Add(column1Value, column2Value);
由于您知道有两列,因此只需遍历行即可。 不必遍历各列。
DataTable table = new DataTable();
table.Columns.Add("FileName", typeof(string));
table.Columns.Add("FilePath", typeof(string));
for (int rows = 0; rows < dataGridView1.Rows.Count; rows++) {
if (!dataGridView1.Rows[rows].IsNewRow &&
dataGridView1.Rows[rows].Cells[0].Value != null &&
dataGridView1.Rows[rows].Cells[1].Value != null) {
table.Rows.Add(dataGridView1.Rows[rows].Cells[0].Value.ToString(), dataGridView1.Rows[rows].Cells[1].Value.ToString());
}
}
如果不知道DataGridView
有多少列,并且您必须遍历这些列……那么您将需要确保DataGridView
中的列至少与DataTable
中的列一样多。
DataTable table = new DataTable();
table.Columns.Add("FileName", typeof(string));
table.Columns.Add("FilePath", typeof(string));
DataRow newRow;
if (dataGridView1.Columns.Count >= table.Columns.Count) {
for (int row = 0; row < dataGridView1.Rows.Count; row++) {
if (!dataGridView1.Rows[row].IsNewRow) {
newRow = table.NewRow();
for (int col = 0; col < table.Columns.Count; col++) {
if (dataGridView1.Rows[row].Cells[col].Value != null)
newRow[col] = dataGridView1.Rows[row].Cells[col].Value.ToString();
else
newRow[col] = "";
}
table.Rows.Add(newRow);
}
}
}
如果您知道dataGridView1.DataSource
是什么对象,则只需访问该对象。 这样会容易得多。
此外,还有一种简单的方法可以将数据从DataGridView导出到Excel:
Ctrl+A
选择DataGridView中的所有单元格。
Ctrl+C
复制它们。
Ctrl+V
粘贴到一张Excel中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.