Datatable from Datagridview(databinding) - c#

I make two datagridviews via msdn a now I need to get datatable from "detailsDataGridView", but I can't convert it.
Error: System.Windows.Forms.BindingSource can't be casted to type System.Data.DataTable.
Any idea?
The code, I have tried.
DataTable d = detailsDataGridView.DataSource as DataTable;
/////////////
DataTable dt = new DataTable();
dt = (DataTable)detailsDataGridView.DataSource;
////////////
BindingSource bs = new BindingSource();
bs.DataSource = detailsDataGridView.DataSource;
DataTable d = (DataTable)(bs.DataSource);
////////////
DataTable data = GetDataTableFromDGV(dgvMyMembers);
private DataTable GetDataTableFromDGV(DataGridView dgv)
{
var dt = ((DataTable)dgv.DataSource).Copy();
foreach (DataGridViewColumn column in dgv.Columns)
{
if (!column.Visible)
{
dt.Columns.Remove(column.Name);
}
}
return dt;
}

Try This Method, This is What you need:
The DataGridView name is detailsDataGridView, so you'll do this :
DataTable data = GetDataTableFromDGV(detailsDataGridView);
Then data is the datatable!
private DataTable GetDataTableFromDGV(DataGridView dgv)
{
var dt = ((DataTable)dgv.DataSource).Copy();
foreach (DataGridViewColumn column in dgv.Columns)
{
if (!column.Visible)
{
dt.Columns.Remove(column.Name);
}
}
return dt;
}
You can see my answer to this Question Here
Good Luck!

Related

sending data from 1 data grid view to another data grid view in another form c#

The following method is used by me to send all rows from a data grid view in a form(datagridview1 of form1) to another data grid view of another form(datagridview1 of form2) when a button is clicked.
private void button2_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
DataTable dt1 = new DataTable();
f2.dataGridView1.DataSource = dt1;
foreach (DataGridView row in dataGridView1.Rows)
{
int n = f2.dataGridView1.Rows.Add();
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
f2.dataGridView1.Rows[n].Cells[col.Index].Value = dataGridView1.Rows[row.Index].Cells[col.Index].Value.ToString();
}
}
}
But no data is sent to datagridview1 of form2! how can i correct this?
Depending on the circumstances, I'd work with a data source, i.e. this way
VB.NET
Dim dt as New DataTable
dt = ds.Tables(0)
Me.DataGridView1.datasource = dt
Form2.DataGridView2.datasource = dt
C#
DataTable dt = new DataTable();
dt = ds.Tables(0);
this.DataGridView1.datasource = dt;
Form2.DataGridView2.datasource = dt;
If you wanted to modify one of them independently, you need a second datatatable:
Dim dt2 as New DataTable
dt2 = dt.Copy() ' copies datatable structure AND the data
Form2.DataGridView2.datasource = dt

I have a list of datatable, how can I copy that list into single datatable in c#

public DataTable LoadPaymentsList()
{
List< DataTable > lstDts = new List< DataTable >();
// Copy into dt
Datatable dt=new Datatable();
return dt;
}
I don't think there's a better way than simple Row- and Column-Adding:
DataTable mergedTable = new DataTable();
List<DataTable> tableCollection = new List<DataTable>();
/*---------------------------------*/
bool columnsAdded = false;
foreach (DataTable table in tableCollection)
{
if (!columnsAdded)
{
foreach (DataColumn column in table.Columns)
{
mergedTable.Columns.Add(column);
}
columnsAdded = true;
}
foreach (DataRow row in table.Rows)
{
mergedTable.Rows.Add(row);
}
}
You want to have a look into merging tables . Check this for further info on dataTable Merging, http://www.c-sharpcorner.com/UploadFile/0c1bb2/merging-multiple-datatables-into-single-datatable-using-asp/
//merging first data table into second data table
dt2.Merge(dt);
dt2.AcceptChanges();

How to cast bindingdatasource to datatable?

I'm trying to cast the bindingdatasource to datatable using this code
BindingSource bs = (BindingSource)gvSideMember.DataSource;
DataTable tCxC = (DataTable)bs.DataSource;
throws error unable to cast bindingsource to datatable
then i tried this code
private DataTable GetDataTableFromDGV(DataGridView dgv)
{
var dt = ((DataTable)dgv.DataSource).Copy();
foreach (DataGridViewColumn column in dgv.Columns)
{
if (!column.Visible)
{
dt.Columns.Remove(column.Name);
}
}
return dt;
}
it again show me same error
DataTable dt = new DataTable();
DataSourceSelectArguments args = new DataSourceSelectArguments();
DataView dv = new DataView();
dv = (DataView)SqlDataSource1.Select(args);
dt = dv.ToTable();
but i don't know what is the base class of DataSourceSelectArguments ? So I can't how can i do this cast?
Looks like your bs.DataSource is actually another BindingSource, so you can try this:
var source = bs.DataSource;
while(source is BindingSource){
source = ((BindingSource)source).DataSource;
}
if(source is DataTable){
var table = (DataTable) source;
}//else there is not any DataTable we can extract.
This is my solution which also works if you are using BindingSource as n child level.
public static DataTable Table(this DataGridView dgv)
{
DataTable dt;
if (dgv.DataSource is BindingSource)
dt = ((BindingSource)dgv.DataSource).Table();
else if (dgv.DataSource is DataSet)
dt = ((DataSet)dgv.DataSource).Tables[dgv.DataMember];
else if (dgv.DataSource is DataTable)
dt = (DataTable)dgv.DataSource;
else
dt = null;
return dt;
}
public static DataTable Table(this BindingSource bs)
{
var bsFirst = bs;
while (bsFirst.DataSource is BindingSource)
bsFirst = (BindingSource)bsFirst.DataSource;
DataTable dt;
if (bsFirst.DataSource is DataSet)
dt = ((DataSet)bsFirst.DataSource).Tables[bsFirst.DataMember];
else if (bsFirst.DataSource is DataTable)
dt = (DataTable)bsFirst.DataSource;
else
return null;
if (bsFirst != bs)
{
if (dt.DataSet == null) return null;
dt = dt.DataSet.Relations[bs.DataMember].ChildTable;
}
return dt;
}

how to store multiple datatable into a single dataset

I have multiple datatable. I want to show all the datatable rows into a single gridview.
How can I do that?
DataTable dtbag101 = (DataTable)Session["bag101"];
DataTable dtwallet111 = (DataTable)Session["wallet111"];
DataSet ds= new DataSet();
ds.Tables.Add(dtbag101);
ds.Tables.Add(dtwallet111);
GridView1.DataSource= ds;
GridView1.DataBind();
The column names for both datatable are the same.
Here I was trying to use dataset but only first DataTable i.e. datbag101 was showing in the gridview.
How can I show all the values in one gridview?
Provided that your two data tables have the same columns, you can UNION them with some handy LINQ.
DataTable dtbag101 = (DataTable)Session["bag101"];
DataTable dtwallet111 = (DataTable)Session["wallet111"];
var result = dtbag101.AsEnumerable().Union(dtwallet111.AsEnumerable());
GridView1.DataSource = result;
GridView1.DataBind();
Otherwise try use DataTable.Merge:
DataTable dtbag101 = (DataTable)Session["bag101"];
DataTable dtwallet111 = (DataTable)Session["wallet111"];
dtbag101.Merge(dtwallet111, true);
GridView1.DataSource = dtbag101;
GridView1.DataBind();
I'm not sure why this isn't working for you. Try this method (grabbed from here):
public static DataTable Union(DataTable First, DataTable Second)
{
//Result table
DataTable table = new DataTable("Union");
//Build new columns
DataColumn[] newcolumns = new DataColumn[First.Columns.Count];
for(int i=0; i < First.Columns.Count; i++)
{
newcolumns[i] = new DataColumn(
First.Columns[i].ColumnName, First.Columns[i].DataType);
}
table.Columns.AddRange(newcolumns);
table.BeginLoadData();
foreach(DataRow row in First.Rows)
{
table.LoadDataRow(row.ItemArray,true);
}
foreach(DataRow row in Second.Rows)
{
table.LoadDataRow(row.ItemArray,true);
}
table.EndLoadData();
return table;
}
Call the method with your two datatables:
GridView1.DataSource = Union(dtbag101, dtwallet111);
You can simply use DataTable.Merge method
DataTable dtbag101 = (DataTable)Session["bag101"];
DataTable dtwallet111 = (DataTable)Session["wallet111"];
dtbag101.Merge(dtwallet111); //Merge action
GridView1.DataSource= dtbag101;
GridView1.DataBind();
I dont know much about this. Just referred it now.
or else
try for loop
DataSet ds = new DataSet();
addTables(dtbag101);
addTables(dtwallet111); //ds will be merge of both tables here
private void addTables(DataTable dt)
{
for(int intCount = ds.Tables[0].Rows.Count; intCount < dt.Rows.Count;intCount++)
{
for(int intSubCount = 0;intSubCount < dt.Columns.Count; intSubCount++)
{
ds.Tables[0].Rows[intCount][intSubCount] = dt.Rows[intCount][intSubCount];
}
}
}
You may need to use DataTable.Merge
DataTable dtAll = new DataTable();
dtAll = dtbag101 .Copy();
dtAll.Merge(dtwallet111, true);
GridView1.DataSource= dtAll;
GridView1.DataBind();
Edit to show how it should work
private void BindGridWithMergeTables()
{
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
dt1.Columns.Add("ID");
dt2.Columns.Add("ID");
DataRow dr1 = dt1.NewRow();
DataRow dr2 = dt2.NewRow();
dr1["ID"] = "1";
dr2["ID"] = "2";
dt1.Rows.Add(dr1);
dt2.Rows.Add(dr2);
DataTable dtAll = new DataTable();
dtAll = dt1.Copy();
dtAll.Merge(dt2, true);
dataGridView1.DataSource = dtAll;
dataGridView1.DataBind();
}

How to write every time to a new row of data table?

How can i insert each time a diffrent row in datatable?
The data table is used in a dataGridView to write a log. I need each time to write in a diffrent line (row) in the datatable, when I can't know how many rows I need in runtime.
Another thing; the datatable is loaded from a XML file, so there might be already rows in the data table.
What can i do? (in short, I always write in the same row) in C#
EDIT:
here is the code:
From some reason, the DateGridView isonly having one row(This is a method that activated in a click of a button)
public void gridStart(string i, string b, string c)
{
DataTable dt = new DataTable();//empty table with no schema
DataColumn colContactID = new DataColumn("Date", typeof(string));
DataColumn colContactName = new DataColumn("Caller", typeof(string));
DataColumn colResult = new DataColumn("Result", typeof(string));
dt.Columns.Add(colContactID);
dt.Columns.Add(colContactName);
dt.Columns.Add(colResult);
DataRow row = dt.NewRow();
row["Date"] = i;
row["Caller"] = b;
row["Result"] = c;
dt.Rows.Add(row);
}
You should be able to Use DataTable.NewRow(). There are several samples on that MSDN page. If you have more questions please provide some sample code to your answer.
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = MyDataTable;
}
private string _fileName = "MyCache.xml";
private DataTable _myDataTable;
public DataTable MyDataTable
{
get
{
if (_myDataTable == null)
{
_myDataTable = new DataTable();
if (File.Exists(_fileName))
_myDataTable.ReadXml(_fileName);
else
InitDataTable(_myDataTable);
}
return _myDataTable;
}
}
private void InitDataTable(DataTable table)
{
table.TableName = "MyTable";
table.Columns.Add("Date", typeof(DateTime));
table.Columns.Add("Caller", typeof(string));
table.Columns.Add("Result", typeof(string));
}
// Have your add code call this method!
private void AddValue(DateTime date, string caller, string result)
{
var row = MyDataTable.NewRow();
row["Date"] = date;
row["Caller"] = caller;
row["Result"] = result;
MyDataTable.Rows.Add(row);
}
protected override void OnClosed(EventArgs e)
{
if (_myDataTable != null)
_myDataTable.WriteXml(_fileName, XmlWriteMode.WriteSchema);
base.OnClosed(e);
}
If it is bound to a data source, you need to first get the data source,
// Assuming it's a DataTable
DataTable dt = ((DataTable)myDataGridView.DataSource);
insert rows to your data source (like what your method is doing in your post), then tell the view to refresh its contents.
So maybe something like this would work:
public void gridStart()
{
DataTable dt = new DataTable();
DataColumn colContactID = new DataColumn("Date", typeof(string));
DataColumn colContactName = new DataColumn("Caller", typeof(string));
DataColumn colResult = new DataColumn("Result", typeof(string));
dt.Columns.Add(colContactID);
dt.Columns.Add(colContactName);
dt.Columns.Add(colResult);
dataGridView1.DataSource = dt;
// Call method to insert values.
}
to start up the grid, and:
public void gridInsert(string i, string b, string c)
{
DataTable dt = (DataTable)myDataGridView.DataSource;
DataRow row = dt.NewRow();
row["Date"] = i;
row["Caller"] = b;
row["Result"] = c;
dt.Rows.Add(row);
// Call another method to refresh grid view.
}
to call when you want to insert data to your DataTable.
My solution:
public partial class _Default : System.Web.UI.Page
{
DataTable tb = new DataTable();
}
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
DataTable dt = new DataTable("table");
dt.Columns.Add(new DataColumn("NR", Type.GetType("System.Int32")));
dt.Columns.Add(new DataColumn("Dihname", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("ing", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("Cost", Type.GetType("System.String")));
Session["ss"] = dt;
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
tb = (DataTable)Session["ss"];
DataRow r1 = tb.NewRow();
r1[0] = ViewState["dishid"].ToString();
r1[1] = ViewState["dishname"];
r1[3] = Label3.Text;
tb.Rows.Add(r1);
DataList5.DataSource = tb;
DataList5.DataBind();
}
}

Categories

Resources