我遇到组合框的问题,我试图从myExcel.xls文件中的数据填充它,但它在组合框中显示System.Data.DataRowView而不是实际值。这是我的代码:
Application excelApp = new ApplicationClass();
string strWB = "myExcel.xls";
string strWBPath = "D:\\TEMP\\";
// Opening Excel file
Workbook workbook = excelApp.Workbooks.Open(strWBPath + strWB, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Worksheet worksheet = (Worksheet)workbook.Sheets.get_Item(1);
Range range = worksheet.UsedRange;
int column = 0;
int row = 0;
DataTable dt = new DataTable();
dt.Columns.Add("Agent Name");
for (row = 2; row <= range.Rows.Count; row++)
{
DataRow dr = dt.NewRow();
for (column = 1; column <= range.Columns.Count; column++)
{
dr[column - 1] = (range.Cells[row, column] as Range).Value2.ToString();
}
dt.Rows.Add(dr);
}
workbook.Close(true, null, null);
excelApp.Quit();
// dataGridView1.DataSource = dt;
comboBox1.DisplayMember = "FirstName";
comboBox1.ValueMember = "Sheet1";
comboBox1.DataSource = dt;
答案 0 :(得分:1)
Value2是一个Object。因此,ToString将返回默认值,即名称而不是值。尝试使用“as string”而不是“.ToString”。
答案 1 :(得分:0)
有没有理由不将comboBox1.DataSource绑定到列表?类似的东西:
dt.AsEnumerable().Select(x => x["FirstName"].ToString()).ToList();