Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如果不重新启动,我无法在Datagridview中看到新元素_C#_Winforms_Datagridview - Fatal编程技术网

C# 如果不重新启动,我无法在Datagridview中看到新元素

C# 如果不重新启动,我无法在Datagridview中看到新元素,c#,winforms,datagridview,C#,Winforms,Datagridview,我已经向底层数据库添加了一条记录,在添加该记录后,我将执行一个 datagridview.Refresh();我没有看到新增加的记录 如果我停止并启动应用程序,它就在那里。我到底在做什么 做什么? 注意:button1和datagridview的形式不同。我公开了datagridview的修饰符。此项目是ado.net项目 public class CustomerService { public List<Customers> ShowAll() {

我已经向底层数据库添加了一条记录,在添加该记录后,我将执行一个 datagridview.Refresh();我没有看到新增加的记录

如果我停止并启动应用程序,它就在那里。我到底在做什么 做什么? 注意:button1和datagridview的形式不同。我公开了datagridview的修饰符。此项目是ado.net项目

public class CustomerService
{
    public List<Customers> ShowAll()
    {
        List<Customers> customers = new List<Customers>();
        SqlConnection conn = new SqlConnection("data source=.; database=custer; user id=sa; password=*****");
        SqlCommand cmd = new SqlCommand(" select * from Customers ", conn.Open());
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            Customer customer = new Customer ()
            {
                CustomerID = dr.GetInt32(0),
                CustomerName = dr.GetString(1),
                CustomerSurname = dr.GetString(2),
            };
            customers.Add(customer);
        }
        conn.Close();
        return customers;
    }
  }

    private void button1_Click(object sender, EventArgs e)
    {
        CustomerService service = new CustomerService();
        if (txtCustomerName.Text != "" || txtCustomerSurname.Text != "")
        {
            customerservice.customerAdd(txtCustomerName.Text, txtCustomerSurname.Text);//this rows is other method .I am using for adding new customer 
            MessageBox.Show("Customer Added");
            Form1.dataGridView1.DataSource = service.ShowAll();
            Form1.dataGridView1.Refresh();
        }
        else
        {
            //……………
        }
    }
公共类客户服务
{
公共列表ShowAll()
{
列出客户=新列表();
SqlConnection conn=newsqlconnection(“数据源=;数据库=custer;用户id=sa;密码=****”;
SqlCommand cmd=newsqlcommand(“从客户处选择*,conn.Open());
SqlDataReader dr=cmd.ExecuteReader();
while(dr.Read())
{
客户=新客户()
{
CustomerID=dr.GetInt32(0),
CustomerName=dr.GetString(1),
CustomerSurname=dr.GetString(2),
};
客户。添加(客户);
}
康涅狄格州关闭();
返回客户;
}
}
私有无效按钮1\u单击(对象发送者,事件参数e)
{
CustomerService=新CustomerService();
if(txtCustomerName.Text!=“| | txtCustomerName.Text!=”)
{
customerservice.customerAdd(txtCustomerName.Text,txtCustomerUrName.Text);//此行是其他方法。我正在使用此方法添加新客户
MessageBox.Show(“客户添加”);
Form1.dataGridView1.DataSource=service.ShowAll();
Form1.dataGridView1.Refresh();
}
其他的
{
//……………
}
}

尝试在datagridview上调用EndEdit:

this.dataGridView1.EndEdit();
其次,刷新网格视图:

this.dataGridView1.Refresh();
如果仍然不起作用,请尝试在包含控件上调用Refresh

ParentControl.Refresh()

这将最终调用可能需要的重新绘制。

通常的方法是重置
DataGridView的
数据源

尝试使用以下代码(使用正确的代码提供正确的数据源):

调用
.Refresh()
无效,因为它只强制重新绘制,但绘制网格的代码不知道更改

请参考此WPF链接,这可能会帮助您:


将数据添加到数据库后,应用程序对添加的数据一无所知。您需要将这些数据加载到内存中。从数据库中检索所有要显示的数据,并在对数据库执行操作后将其显式绑定到UI

编辑

您能否检查ShowAll()在调试时返回的内容?它是否返回您实际需要的数据?

如果是WPF应用程序,请看一看。这里的问题是告诉您的UI组件底层数据源已经更改,因此UI组件反映了对数据所做的更改

同样,如果它是WPF应用程序,您可以将数据定义为ObservableCollection,并将UI绑定到此集合。ObservableCollection会在数据发生更改时自动请求UI刷新


Rica ederim。)

customerservice.customerAdd的内容是什么? 可能它没有正确地关闭连接/没有将数据刷新到数据库中,并且只有在您关闭应用程序时才会发生(所有内存都已释放,所有连接都已关闭/刷新)


另外-我建议使用网格绑定到的BindingSource,并更改其数据源-如果网格的数据源已更改,它会自动通知网格,这将导致网格刷新。

正如您所说,这些格式不同,我认为指向Form1的指针不会指向您想要的格式。您应该使用
this
将该表单的指针传递到此表单

创建表单2时,请定义如下:

Form2 = new Form2();
Form2.form1 = this; 

那么你的代码应该可以工作。

看起来你正在使用一个列表作为数据源。我发现,对于只读数据,使用通用列表是可以的,但是对于任何类型的更新,您都需要更强大的功能。我不知道WPF,但在winForms中,我在IBindingList接口和BindingList通用集合方面取得了巨大成功。BindingList泛型集合为您实现IBindingList接口。我会阅读MSDN关于这两个方面的文章。我已经基本停止使用IBindingList接口,但它仍然可以很好地实现


答案是将gridview连接到
绑定列表
,而不是
列表
。希望这能解决您的问题…

如果您将列表更改为BindingList,您将获得成功。我创建了一个示例,它在表单上有一个DataGridView和几个按钮

button1生成一些假数据并分配数据源。 按钮2将另一个客户添加到基础列表中

DataGridView在基础BindingList更改时更新

代码:

公共类客户
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共字符串姓氏{get;set;}
}
公共部分类Form1:Form
{
BindingList客户=新建BindingList();
公共表格1()
{
初始化组件();
}
私有无效按钮1\u单击(对象发送者,事件参数e)
{
对于(int i=0;i<10;++i)
{
客户。添加(新客户)
{
Id=i,
Name=“Name”+i,
姓氏=“姓氏”+i
});
}
dataGridView1.DataSource=客户;
}
私有无效按钮2\u单击(对象发送者,事件参数e)
{
客户。添加(新客户)
{
Id=22,
Name=“Newname”,
姓氏=“Newsurname”
});
}
}
现在,这种方法之所以有效,是因为
BindingList
实现了
IBindingList
,以及其他功能,
Form2 = new Form2();
Form2.form1 = this; 
public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string SurName { get; set; }
}

public partial class Form1 : Form
{
    BindingList<Customer> customers = new BindingList<Customer>();
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < 10; ++i)
        {
            customers.Add(new Customer
            {
                Id = i,
                Name = "Name" + i,
                SurName = "Surname" + i
            });
        }
        dataGridView1.DataSource = customers;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        customers.Add(new Customer
        {
            Id = 22,
            Name = "Newname",
            SurName = "Newsurname"
        });
    }
}
public class CustomerService
{
  public DataTable ShowCustomers()
  {
    string cns = "data source=.; database=custer; user id=sa; password=*****";
    SqlConnection conn = new SqlConnection(cns);
    SqlDataAdapter da = new SqDataAdapter("select * from Customers", conn);
    DataTable dt = new DataTable();
    da.Fill(dt);
    return dt;
  }
}    
private void button1_Click(object sender, EventArgs e)
{
   CustomerService service = new CustomerService();
   if (txtCustomerName.Text != "" || txtCustomerSurname.Text != "")
   {
     customerservice.customerAdd(txtCustomerName.Text,txtCustomerSurname.Text);
      MessageBox.Show("Customer Added");
      DataTable dt = service.ShowCustomers();
      Form1.dataGridView1.DataSource = dt;
      //If you also need customer list. Provide the DataTable and get list
      List<Customers> customers = new List<Customers>();        
      for (int i=0;i<dt.Rows.Count;i++)
      {
        Customer customer = new Customer();            
        customer.CustomerID = Convert.ToInt32(dt.Rows[i][0]);
        customer.CustomerName = dt.Rows[i][1].ToString();
        customer.CustomerSurname = dt.Rows[i][2].ToString();
        customers.Add(customer);
      }
   }
}
class CustomerService {
    List<Customers> customers;
    ...
}
BindingSource binding = new BindingSource();
binding.DataSource = customers;
dataGridView1.DataSource = binding;
DataGrid.CommitEdit();
DataGrid.Items.Refresh();