数据绑定:'System.Char'不包含名称为"客户"的属性


 protected void Button_Upload_Click(object sender, EventArgs e)
 {
    if (FileUpload1.HasFile)
    {
        FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Data/" + FileUpload1.FileName));
    }
    string path = Server.MapPath("~/Data/" + FileUpload1.FileName);
    string[] readtext = File.ReadAllLines(path);

    StringBuilder strbuild = new StringBuilder();
    foreach (string s in readtext)
    {
        strbuild.Append(s);
        strbuild.AppendLine();
    }
    ListBox1.DataValueField = strbuild.ToString();
    ListBox1.DataTextField = strbuild.ToString();
    ListBox1.DataSource = strbuild.ToString();
    ListBox1.DataBind();

在这里,我上传了包含客户详细信息的文件。当我选择文件时,它显示错误,例如

数据绑定:"System.Char"不包含名为 XXX 的属性。

我必须改变什么?

我认为StringBuilder在这种情况下效率不高。最佳选择是为客户创建一个具有name属性的类,id然后从输入数据创建一个列表并将其绑定到列表。此处的文件格式未知,并且不会向您提供有关该文件的任何详细信息。因此,在这里我向您展示一个如何从列表绑定列表框的示例;

        List<string> strList = File.ReadAllLines(@"C:UsersSujithDesktopsujithAllcredentials.txt").ToList();
        ListBox1.DataSource = strList;
        ListBox1.DataBind(); 

DataBinding 不是这样工作的。您必须创建列表然后存储其中的每一行

List<string> strList = new List<string>();
foreach (string s in readtext)
{
    strbuild.Add(s);
}
ListBox1.DataSource = strList;
ListBox1.DataBind();

或者你可以简单地从你阅读的内容中输入字符串数组

ListBox1.DataSource = readText;

Gilang的答案应该有效,但是有一个特殊的类设计用于绑定 - BindingList。您的代码应如下所示:

var bindingList = new BindingList<string>(readText);
ListBox1.DataSource = bindingList;
ListBox1.DataBind();

因此,列表框的项目列表中的所有更改(添加或删除)都正确捕获在数据源中 - 您实际上具有two way binding

注意:尝试为变量使用有意义的名称,否则代码在增长时将变得非常难以阅读:

`ListBox1` -> `lstCustomers` or `CustomersList` 
`readText` -> `readLines` or `customerNames`

最新更新