Skip to main content
 首页 » 编程设计

c#之Winforms 如何绑定(bind)到 Listlong> DatagridView 并使其正确显示

2024年02月13日12dudu

所以我需要在网格中显示人们输入的数字列表,以帮助他们仔细检查他们的工作。它几乎可以工作,只是它不显示数字。我的设置很简单。我有一个文本框,他们输入数字,当单击添加按钮时,它被添加到 BindingList,然后用作 DataGridView 的数据源。

因此,在这个 Stackoverflow Post 的帮助下我能够做到这一点。 不幸的是,即使每次它都没有正确显示值时,它似乎在 Grid 中添加了一行。 它将新行显示为空。

这是我的代码。

   public partial class ManualEntry : Form 
   { 
 
    BindingList<long> ProjectIDs; 
    public ManualEntry() 
    { 
        InitializeComponent(); 
        ProjectIDs = new BindingList<long>(); 
    } 

单击添加按钮时,将执行此操作。

        private void AddButton_Click(object sender, EventArgs e) 
        { 
            try 
            { 
               long temp = long.Parse(textBox1.Text); 
               ProjectIDs.Add(temp); 
               ProjectsGrid.DataSource = ProjectIDs; 
               textBox1.Text = "";//clear the textbox so they can add a new one. 
            } 
            catch//bring up the badinput form 
            { 
                BadInput b = new BadInput(); 
                b.Show(); 
            } 
 
        } 

这是添加几个数字的结果。

如果您需要我提供任何其他代码来帮助您回答问题,请尽管询问。

请您参考如下方法:

您还没有告诉 DataGridViewColumn 要绑定(bind)到什么。

通常您绑定(bind)到绑定(bind)数据类型的公共(public)属性。在这种情况下,您的数据类型是 long,它没有合适的属性可以绑定(bind)。

将您的 long 包装在自定义类中并将其公开为公共(public)属性。

public class Data 
{ 
    public long Value { get; set; } 
} 

将您的列绑定(bind)到 Value 属性。您可以在设计器中执行此操作,但这里是代码:

Column1.DataPropertyName = "Value"; 

现在您使用 Data 而不是 long:

ProjectIDs = new BindingList<Data>(); 

...

long temp = long.Parse(textBox1.Text); 
ProjectIDs.Add(new Data { Value = temp });