ComboBox 显示 DataRowView 而不是实际值

发布于 2024-11-27 00:20:53 字数 1038 浏览 1 评论 0原文

我的组合框有问题,我尝试从 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;

I have a problem with the combobox, I tried to populate it from data that is in myExcel.xls file but it is displaying System.Data.DataRowView in the combobox instead of the actual values.Here is my code:

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;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

泪是无色的血 2024-12-04 00:20:53

Value2 是一个对象。因此,ToString 将返回默认值,即名称而不是值。尝试使用“as string”而不是“.ToString”。

Value2 is an Object. As such, ToString will return the default which is the name rather than the value. Try using "as string" rather than ".ToString".

紫轩蝶泪 2024-12-04 00:20:53

有什么理由不将comboBox1.DataSource绑定到列表吗?像这样的东西:

dt.AsEnumerable().Select(x => x["FirstName"].ToString()).ToList();

Is there any reason not to bind comboBox1.DataSource to a list instead? Something like:

dt.AsEnumerable().Select(x => x["FirstName"].ToString()).ToList();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文