开发者

updating datagridview table

I'm new at this programming thing and it's fun!

At the moment I'm looking at the DataGridView and arraylists.

In my array I have names and addresses and such...

and by a click of a button I set the datasource for the datagridview to my arraylist like this:

    private void button1_Click(object sender, EventArgs e)
    {
        dataGridView1.DataSource = logik.kundekartotek.arrKunder;
    }

but when I add some new information to my arraylist I need to update the datagridview..

but how do I do that?

I found a solution:

    private void button1_Click(object sender, EventArgs e)
    {
        dataGridView1.DataSource = null; 
        dataGridView1.DataSource = logik.kundekart开发者_StackOverflow社区otek.arrKunder;
    }

but that doesn't seem right..


Try this:

private void button1_Click(object sender, EventArgs e)
{
    dataGridView1.DataSource = logik.kundekartotek.arrKunder;
    dataGridView1.EndEdit();
}

private void button2_Click(object sender, EventArgs e)
{
    dataGridView1.Refresh();
}

EndEdit is described here.


One option could be to add new row to the DataGridView yourself. On adding new item to the array that you have, you could do,

  int i = dataGridView1.Rows.Add();//i is the index of the new row added

    dataGridView1.Rows[i].Cells[0].Value = val1;
    dataGridView1.Rows[i].Cells[1].Value = val2;

If lets suppose, one of your column value is of DateTime, you could do

dataGridView1.Rows[i].Cells[1].ValueType = typeof(DateTime);


When you use an ArrayList as your DataSource then what you are doing is the best way of updating the displayed informmation however there are collection types that are far better for using as the DataSource which have been designed to support two way databinding.

The first thing to look at is the generic BindingList<T> collection. It is described fully here on MSDN.

With a BindingList<T> instead of the ArrayList when you add new objects to the list (using the .Add() method) they will automatically appear in the DataGridView.

Once you have started using that you will probably want more features such as sorting the grid by column - browse through MSDN for more examples of what is possible.

(another DataSource option that gives advanced functions is the DataTable just as with the BindingList<T> when you add an item to a DataTable it appears in the DataGridView but I'd recommend using the list, datatables either bind you to a specific data access technololgy or force you to jump through a lot of hoops).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜