简体   繁体   中英

DataGridView is not updating after second row

i am trying a few things in WinForms for the first time. I have a problem which appears very trivial to me but then i am not a WinForms guy.. searched a lot but could not find the solution.

Below is the code, don't worry about the content itself, its just test code. The problem is that when i click the AddNew button a row gets added to gridview but after that no row gets added, no matter how many times user clicks on the AddNew button. You can see that in the Image below.

Can you point out why no rows are getting added to the gridview after a row has been added. AddNew button just works for one click. While as it should add the second row again and again.

Thanks in advance.

    public partial class JobCard : UserControl
    {
        List<Work> works = new List<Work>();
        BindingSource bs = new BindingSource();

        public JobCard()
        {
            InitializeComponent();

            works.Add(new Work() { S_No = 1, JobCategoryId = 1, JobCategoryName = "electricals", JobId = 1, JobName = "lights", Labour = 1, MaterialName = "tape", PartName = "headlight" });

            bs.DataSource = works;
            dataGridView1.AutoGenerateColumns = true;
            dataGridView1.DataSource = bs;
         }

        private void btnAddNew_Click(object sender, EventArgs e)
        {
            works.Add(new Work() { S_No = 2, JobCategoryId = 2, JobCategoryName = "electricals", JobId = 2, JobName = "lights", Labour = 2, MaterialName = "tape", PartName = "headlight" });
            dataGridView1.DataSource = works;
        }

     }

应用快照

You need to reset the datasource of your bindingsource.

Try

private void btnAddNew_Click(object sender, EventArgs e)
{
   ...
   bs.DataSource = null;
   bs.DataSource = works;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM