其他信息:复杂数据绑定接受 IList 或 IListSource 作为数据源

本文关键字:IListSource 数据源 IList 信息 复杂 数据绑定 其他 | 更新日期: 2023-09-27 18:31:51

我正在尝试在 excel 工作表中选择总计并将其添加到列表框中,每个列表都在新行中。

private void btn_update_Click(object sender, EventArgs e) {
    for (int i = list_sheetnames.Items.Count -1; i >= 0; i--) {
        string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + textBox_filename.Text + ";Extended Properties='Excel 12.0 XML;HDR=YES;';";
        string selectCmd = "Select SUM(Total) As Total_SUM From [" + list_sheetnames.Items[i] + "$]";
        using(OleDbConnection excelConn = new OleDbConnection(connString)) {
          excelConn.Open(); 
          OleDbCommand command = new OleDbCommand(selectCmd, excelConn);
          OleDbDataAdapter da = new OleDbDataAdapter(command);
          DataTable sheetInfo = new DataTable();
          da.Fill(sheetInfo);
          //Do something with the data.
          //list_total.Items.Add(sheetInfo);
          list_total.DataSource = da.ToString();
        }
    }
}

我收到错误

其他信息:复杂数据绑定接受 IList 或 IListSource 作为数据源

看起来您正在尝试将数据表绑定到列表。我猜List_total是List<string>?如果要从数据表中添加值,则需要遍历行和项才能获得所需的内容。

foreach (var row in da.Rows)
{
    foreach (var item in row.ItemArray)
    {
        //do your checks on the data here and add it to your list if necessary.
        list_total.Add(item.ToString());
    }
}

您也可以尝试传统的 for 循环,如下所示:

for (int i = 0; i < da.Rows.Count; i++)
{
    list_total.Add(da.Rows[i]["Total_SUM"].ToString());
}

更新
所以你的代码现在是:

List<string> lst = new List<string>(); 
foreach (DataRow r in sheetInfo.Rows) 
{ 
    string sheettotal = (string)r["Total_SUM"].ToString();
    lst.Add(sheettotal); 
}
list_total.DataSource = lst;