【问题标题】:Additional information: Complex DataBinding accepts as a data source either an IList or an IListSource附加信息:Complex DataBinding 接受 IList 或 IListSource 作为数据源
【发布时间】:2016-01-26 12:53:46
【问题描述】:

我正在尝试在 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();
        }
    }
}

我遇到了一个错误

【问题讨论】:

  • 你得到哪个错误?
  • 我稍微改写了你的问题,请包括错误

标签: c# list


【解决方案1】:

您似乎正在尝试将数据表绑定到列表。我猜 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;

【讨论】:

  • 我没听明白,请你说清楚我的意思是我在哪里可以添加此代码以及如何配置它
  • @AbdullazizHappy - 在您执行“list_total.DataSource = da.ToString();”的地方。您不能将数据表作为数据源添加到列表中。相反,您需要通过数据表将各个条目添加到列表中。
  • row.ItemArray is not available here is theedited code DataTable sheetInfo = new DataTable(); da.Fill(sheetInfo);字符串总计=sheetInfo.ToString(); foreach(sheetInfo.Rows 中的 var 行){ foreach(row.ToString() 中的 var 项){ list_total.Items.Add(item.ToString()); } }
  • @AbdullazizHappy - row.ToString() 不起作用。您需要遍历行中的项目。
  • @AbdullazizHappy - 用替代解决方案更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-06
相关资源
最近更新 更多