Click here to Skip to main content
15,309,768 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
It is possible use build-in method to update datasource from datagridview or commit changes from datagridview to datasource? Otherwise how can I get datatable from datagridview?
I have dataset to set as datasource for datagridview. When I change datagridview (delete/insert for columns/rows), datasource not changed - is ordinary (still have same columns/rows as on begin). I want update datasource according datagridview, because I need final datatable from datagridview. Datatable I get using
((DataTable)dataGridView1.DataSource).DefaultView.ToTable().Copy()
but this datatable = datasource but datatable <> datagridview
I want
datatable = datagridview

(I have created own method who read data from datagridview and write to datatable (using loop foreach for each cell))

thank you
Posted
Updated 3-Dec-21 23:28pm

HTML

public static DataTable ToDataTable<T>(IList<T> list)
       {
           PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
           DataTable table = new DataTable();
           for (int i = 0; i < props.Count; i++)
           {
               PropertyDescriptor prop = props[i];
               table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
           }
           object[] values = new object[props.Count];
           foreach (T item in list)
           {
               for (int i = 0; i < values.Length; i++)
                   values[i] = props[i].GetValue(item) ?? DBNull.Value;
               table.Rows.Add(values);
           }
           return table;
       }



put this code in code behind(.cs) file nothing to changes in this code

then

you have to add 1 line when you have to bind gridview add this line below dataset


 DataTable dt = ToDataTable(your_tablename.ToList());
GridviewId.DataSource = dt;
          
GridviewId.DataBind();



i hope it will help you......
   
v2
Comments
smoula99 6-Sep-13 5:27am
   
I need "convert/transfer" updated data from datagridview to datatable/datasource/dataset (not reverse)

I wrote something like this:

private DataTable GetDataGridViewAsDataTable(DataGridView _DataGridView)
{
try
{
if (_DataGridView.ColumnCount == 0) return null;
DataTable dtSource = new DataTable();
//////create columns
foreach (DataGridViewColumn col in _DataGridView.Columns)
{
if (col.ValueType == null)
dtSource.Columns.Add(col.Name, typeof(string));
else
dtSource.Columns.Add(col.Name, col.ValueType);
dtSource.Columns[col.Name].Caption = col.HeaderText;
}
///////insert row data
foreach (DataGridViewRow row in _DataGridView.Rows)
{
DataRow drNewRow = dtSource.NewRow();
foreach (DataColumn col in dtSource.Columns)
{
drNewRow[col.ColumnName] = row.Cells[col.ColumnName].Value;
}
dtSource.Rows.Add(drNewRow);
}
return dtSource;
}
catch { return null; }
}
Hi,

You can get datatable by using the datasource property of DataGridview.
By this way
C#
Datatable  dtGridSource  = (DataTable)datagridview.DataSource;


Hope this helps.
   
Comments
smoula99 6-Sep-13 5:12am
   
for example
if original datasource have a 5 columns and bind to datagridview and then I add to datagridview 2 new columns
using your solution datatable will have 5 columns instead 7 columns (5 orginal + 2 new)
bitofweb 6-Sep-13 5:39am
   
i just tried this with 3 column datatable and bind only 2 columns to datagridview, while using my solution i am getting only 3 columns only and no new columns.
make sure you have set AutoGenerateColumns to false.
If this does not helps share your code i'll try to find the bug and will try provide easy solution.
smoula99 6-Sep-13 6:01am
   
i think, it must be easy something like you suggest (setting something properties or ???)

when I set AutoGenerateColumns to false, then I don't add new columns to datagridview

My code is:
DataSet ds - "contains my data - example datatable columns count = 5"
dataGridView1.DataSource = ds;
dataGridView1.Columns.Insert(1, "new DataGridViewColumn() - insert a 1 new columns")
Datatable dtGridSource = (DataTable)dataGridView1.DataSource;
dtGridSource contains only 5 columns instead 6

if use AutoGenerateColumns = false
dataGridView1.DataSource = ds;
dataGridView1.AutoGenerateColumns = false;
dataGridView1.Columns.Insert(1, "new DataGridViewColumn() - insert a 1 new columns") - then I can't add new columns to datagridview
Datatable dtGridSource = (DataTable)dataGridView1.DataSource;
dtGridSource contains only 5 columns
bitofweb 6-Sep-13 6:19am
   
you binding datasource to dataset, try to bind datatable or ds.Tables[0] or ds.Tables["Table Name"]
do you have any specific need as explicitly adding column to datagridview.
smoula99 6-Sep-13 6:30am
   
yes, i make typist's error
dataGridView1.DataSource = ds.Tables[0]; - this is correct

but still, no columns/rows how need

when I use AutoGenerateColumns by inicialize
InitializeComponent();
dataGridView1.AutoGenerateColumns = false;

no data are displayed in datagridview
bitofweb 6-Sep-13 6:50am
   
you need to add the columns to data gridview.
Follow these steps

1. Go to Designer > selected Datagridview > Select Properties(F4) > Click on Columns.
this will open new dialog.
2. On Bottom left of Dialog Click Add Button, this will open the Dialog in that choose the name of column, type of column and column header text and click in add. This will add column to your grid view and in the right pane choose property DataPropertyName under Data section.
3. Repeat this for no. of columns you want to add.
4 Make sure the name you provide in datasource property should match with the columns name in your datatable.
5. Add datasource source to the gridview.
smoula99 6-Sep-13 7:19am
   
I use datagridview for many options (in first option is > 60 colums, for second option is < 10 columns, etc.) I can't create columns "static", because I have different many columns (and rows). When I have only static count columns, then I can create just like you write.
I load datatable who have > 60 colums, that I processing (manual or programmatic) and unnecessary columns and row I delete. And I need datatable from this processing data in datagridview

i can do this processing in datatable instead datagridview, but insert new columns and next delete columns in datatable will cause shift position new added columns (unless at firt delete columns and next add columns)
bitofweb 6-Sep-13 7:25am
   
i also tried adding columns dynamically and working properly.
Also explain why u r adding this line
dataGridView1.Columns.Insert(1, "new DataGridViewColumn() - insert a 1 new columns")
smoula99 6-Sep-13 7:29am
   
I wrote this line (dataGridView1.Columns.Insert(1, "new DataGridViewColumn()...) - symbolic

full code for insert columns to datagridview is:
DataGridViewColumn _addColumns = new DataGridViewColumn();
_addColumns.Name = "something name";
_addColumns.HeaderText = "something name";
_addColumns.ValueType = typeof(string);
_addColumns.CellTemplate = new DataGridViewTextBoxCell();
dataGridView1.Columns.Insert(5, _addColumns); //5 is position of insert columns
public DataTable GetDTfromDGV(DataGridView dgv,int rowcount = 0,int colcount=0)//row count used when rowpost paint used, default is zero...colcount is the coulmns needed to convert , default is 0
        {
            DataTable dt = new DataTable();
            int coulmneeded = dgv.Columns.Count - (dgv.Columns.Count-colcount);

            for (int ik = 0; ik < coulmneeded; ik++)
            {
                dt.Columns.Add(dgv.Columns[ik].HeaderText);
            }

            

            for (int i = 0; i < dgv.Rows.Count - rowcount; i++)
            {
                var dr = dt.NewRow();
                for (int j = 0; j < coulmneeded; j++)
                {
                    dr[j] = dgv.Rows[i].Cells[j].Value;
                }
                dt.Rows.Add(dr);
            }
            

            return dt;
        }
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900