开发者

ComboBox displays DataRowView instead of actual values

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 workb开发者_开发百科ook = 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;


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".


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜