Add a Row After Setting DataSource to Datagridview

亡梦爱人 提交于 2019-12-03 10:26:46
LarsTech

Try using a BindingList instead of List:

BindingList<MyClass> li = new BindingList<MyClass>();

Then you add or delete records from the list itself:

li.Add(new MyClass() { Id = 15, LastName = "Z", Name = "Agent" });

and the grid will automatically show that new row.

To have the individual property updates automatically appear in the grid, then your class needs to implement the INotifyPropertyChanged interface:

public class MyClass : INotifyPropertyChanged {
  public event PropertyChangedEventHandler PropertyChanged;

  protected void OnPropertyChanged(string propertyName) {
    if (PropertyChanged != null) {
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
  }

and then your property would have to raise the event:

private string lastName = string.Empty;

public string LastName {
  get { return lastName; }
  set {
    if (value != lastName) {
      lastName = value;
      OnPropertyChanged("LastName");
    }
  }
}

Now if you update a row from code, the grid will show that update:

li[1].LastName = "Q";

Also see Implementing INotifyPropertyChanged - does a better way exist?

Here is the solution for adding rows to a data source after it is bound to a DataGridView.

Please note that I have used a blank DataGridView "Mydgv" and Button "button1" in the form.

Also I have used the same "MyClass" from your question.

Put one Button named "button1" in the form and write this code

    private void button1_Click(object sender, EventArgs e)
    {
        List<MyClass> li = (List<MyClass>)Mydgv.DataSource;
        MyClass O = new MyClass();

        O.Name = "XYZ";
        O.LastName = "G";
        O.Id = new Random().Next(10, 100);
        li.Add(O);

        Mydgv.DataSource = li.ToList<MyClass>();
    }

Click on the button and you can see your DataGridView is updated with the new row.

Instead of setting the same List object as DataSource try a list of MyClass as I noted below.

Mydgv.DataSource = li.ToList<MyClass>();

To make it easier to understand I put the Id as a Random number between 10 and 100.

Hope you will check it and reply me if there are any problem with the code.

Follow thos Steps..

  1. Create a Property of ObservableCollection of MyClass.

    private ObservableCollection<MyClass> _li;
    
    public ObservableCollection<MyClass> Li
    {
        get; 
        set
        {
            _li = value;
            NotifyPropertyChangedEvent("Li");      
        }
    }
    
  2. Bind DataGrid DataSource to "Li" property in XAML file.

  3. Now whenever the collection is updated(i.e items added or deleted), the DataSource will update automatically.

create global

List<Myclass> li = new List<MyClass>();

Out side of Page_load or any function

Add/remove any row from li inside of any function and call below line when you change data in li

gridview.DataSource=li;
gridview.DataBind();

@Co. Aden

As per what I see everything that you did in the first part of binding the list to grid as data source is fine. Execpet that you have missed to call the databind Method after providing the datasource.

Once you call the DataBind method, the details should be displayed on the grid as per what ever you expected.

Mydgv.DataBind();

Sample for Reference:

C#:

public partial class home : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        List<Student> students = new List<Student>();
        for (int i = 0; i < 10; i++)
        {
            students.Add(new Student(){FirstName = "First Name - " +i.ToString(),LastName = "Last Name - "+i.ToString()});
        }
        students.Add(new Student() { FirstName = " ", LastName = " " });
        UsingDataSourceAndDataBind(students);

    }

    private void UsingDataSourceAndDataBind(List<Student> students)
    {
        GridView1.DataSource = students;
        GridView1.DataBind();
    }
}

class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

ASPX Code:

<body>
<form id="form1" runat="server">
<div>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
</div>
</form>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!