Click here to Skip to main content
15,897,704 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......
 
Share this answer
 
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.
 
Share this answer
 
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
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;
        }
 
Share this answer
 

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