【问题标题】:DataGridView not loading data programmaticallyDataGridView 未以编程方式加载数据
【发布时间】:2019-01-17 10:02:40
【问题描述】:

我正在开发一个 Windows 应用程序,当用户单击按钮 (Add) 时,我从 TextBox 获取输入并将其添加到 DataGridView。

我的问题是,当我第一次添加文本时,它可以正常工作并添加到网格中。
当我添加新文本时,它不会添加到 DataGridView。一旦表单关闭并使用相同的对象重新打开,我就可以看到它。

代码:

private void btnAddInput_Click(object sender, EventArgs e)
{
    if (Data == null)
        Data = new List<Inputs>();

    if (!string.IsNullOrWhiteSpace(txtInput.Text))
    {
        Data.Insert(Data.Count, new Inputs()
        {
            Name = txtInput.Text,
            Value = string.Empty
        });
    }
    else
    {
        MessageBox.Show("Please enter parameter value", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }

    txtInput.Text = "";
    gridViewInputs.DataSource = Data;
}

我不确定是什么导致第二次单击添加按钮时记录未添加到网格中。

【问题讨论】:

  • 你有什么错误吗?
  • 尝试使用gridViewInputs.DisplayMember = "Name";
  • 当您不需要跟踪索引时,为什么要使用Data.Insert()?我会使用简单的Data.Add() - 当列表填充量很大以及删除元素时,它也会具有性能优势。

标签: c# winforms datagridview


【解决方案1】:

您可以在设置新的之前将DataGridView.DataSource 设置为null
这将导致 DataGridView 使用源 List&lt;Inputs&gt;:
中的新数据刷新其内容 仅当 DataSource 引用与当前引用不同或设置为 null 时,才会重置底层 DataGridViewDataConnection

请注意,当您重置 DataSource 时,会多次引发 RowsRemoved 事件(每删除一行一次)。

我建议将List 更改为BindingList,因为对列表的任何更改都会自动反映,并且如果/需要时,它将允许从 DataGridView 中删除行:使用 @987654333 @ 因为 DataSource 不允许删除一行。

BindingList<Inputs> InputData = new BindingList<Inputs>();

如果您不希望您的用户篡改网格内容,您始终可以将AllowUserToDeleteRowsAllowUserToAddRows 属性设置为false

例如:

public class Inputs
{
    public string Name { get; set; }
    public string Value { get; set; }
}

internal BindingList<Inputs> InputData = new BindingList<Inputs>();

private void Form1_Load(object sender, EventArgs e)
{
    dataGridView1.DataSource = InputData;
}

private void btnAddInput_Click(object sender, EventArgs e)
{
    string textValue = txtInput.Text.Trim();
    if (!string.IsNullOrEmpty(textValue))
    {
        InputData.Add(new Inputs() {
            Name = textValue,
            Value = "[Whatever this is]"
        });
        txtInput.Text = "";
    }
    else
    {
        MessageBox.Show("Not a valid value");
    }
}

如果您想继续使用List&lt;T&gt;,请添加重置DataGridView.DataSource 所需的代码:

private void btnAddInput_Click(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(textValue))
    {
        //(...)
        dataGridView1.DataSource = null;
        dataGridView1.DataSource = InputData;
        txtInput.Text = "";
    }
    //(...)

【讨论】:

    猜你喜欢
    • 2012-11-12
    • 2014-12-02
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多