How to cast bindingdatasource to datatable? - c#

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;
}

Related

How to bind Dataset to TreeView in C#.Net [duplicate]

This question already has answers here:
How do you databind to a System.Windows.Forms.Treeview control?
(3 answers)
Closed 8 years ago.
I have created a DataTable with three columns and i am adding rows to that DataTable using Data Rows. Then,I am adding the DataTable to a DataSet. Now, I just want to bind the DataSet to a TreeView.
DataTable dt = new DataTable();
dt.TableName = "Tree";
dt.Columns.Add("Name");
dt.Columns.Add("Project");
dt.Columns.Add("Experience");
List<Profile> list = new List<Profile>
{
new Profile{ Name="Boopathi", Project="NPD", Experience=1},
new Profile{ Name="Stephan", Project="Luxstone", Experience=1},
new Profile{ Name="Sri", Project="DellAsap", Experience=1}
};
var query = from s in list.AsEnumerable()
where s.Experience == 1
select s;
DataSet ds=new DataSet();
DataRow dr = dt.NewRow();
foreach (var t in query)
{
dr["Name"] = t.Name;
dr["Project"] = t.Project;
dr["Experience"] = t.Experience;
}
ds.Tables.Add(dt);
return ds;
Try this
if (ds.Tables.Count > 0)
{
TreeNode root= new TreeNode("Root Node");
foreach (DataRow row in ds.Tables[0].Rows)
{
TreeNode NewNode = new TreeNode(row["Name"].ToString());
root.ChildNodes.Add(NewNode);
}
}
DataTable dt=new DataTable();
DataTable dt1 = new DataTable();
DataSet ds = new DataSet();
ds.Tables.Add(dt);
ds.Tables.Add(dt1);
ds.Relations.Add("children", dt.Columns["GSICCodeID"], dt1.Columns["GSICCodeID"]);
if (ds.Tables[0].Rows.Count > 0)
{
tvSicCode.Nodes.Clear();
Int32 i = 0;
foreach (DataRow masterRow in ds.Tables[0].Rows)
{
TreeNode masterNode = new TreeNode((string)masterRow["Description"], Convert.ToString(masterRow["GSicCodeID"]));
tvSicCode.Nodes.Add(masterNode);
foreach (DataRow childRow in masterRow.GetChildRows("Children"))
{
TreeNode childNode = new TreeNode((string)childRow["SICCodeDesc"], Convert.ToString(childRow["SICCodeID"]));
if (Convert.ToString(ds.Tables[1].Rows[i]["CarrierSICCode"]) != "")
childNode.Checked = true;
masterNode.ChildNodes.Add(childNode);
i++;
}
}
tvSicCode.CollapseAll();
}
here is a simple article also
using telerik :
using System.Data.SqlClient;using Telerik.Web.UI;
namespace RadTreeView_DataBindDataTable
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindToDataTable(RadTreeView1);
}
}
private void BindToDataTable(RadTreeView treeView)
{
SqlConnection connection = new SqlConnection(Properties.Settings.Default.NwindConnectionString);
SqlDataAdapter adapter = new SqlDataAdapter("select CategoryID, CategoryName, Description from Categories", connection);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
treeView.DataTextField = "CategoryName";
treeView.DataFieldID = "CategoryID";
treeView.DataValueField = "Description";
treeView.DataSource = dataTable;
treeView.DataBind();
}
}
}

dataTable.DefaultView.Rowfilter always returning first row

I've been trying to make a search function for a dataTable. My problem is that the first row of the table is ALWAYS within the filtered rows, even when the boolean column is actually changed to a zero.
Here is my search code:
private void buscar()
{
DataTable dataTable;
if (!verTodos)
{
dataTable = DBHelper.Instance.ProductosConStock();
}
else
{
dataTable = DBHelper.Instance.ProductosTodos();
}
dataGridProductos.DataSource = dataTable.DefaultView;
foreach (DataGridViewRow row in dataGridProductos.Rows)
{
if (row.Cells[0].Value.ToString().ToUpper().Contains(txtBusqueda.Text.ToString().ToUpper()) ||
row.Cells[1].Value.ToString().ToUpper().Contains(txtBusqueda.Text.ToString().ToUpper()) ||
row.Cells[2].Value.ToString().ToUpper().Contains(txtBusqueda.Text.ToString().ToUpper()))
{
row.Cells[4].Value = 1;
}
else
{
row.Cells[4].Value = 0;
}
}
dataTable.DefaultView.RowFilter = "mostrar = 1";
}
Try creating a DataView from your datatable and run the filter based on that.
Below is a quick example i tried and it works fine.
DataTable dt = new DataTable();
dt.Columns.Add("bool", typeof(Boolean));
dt.Rows.Add(true);
dt.Rows.Add(false);
dt.Rows.Add(true);
DataView dv = new DataView(dt);
dv.RowFilter = "bool = 1";
foreach (DataRowView drv in dv)
{
Console.WriteLine(drv[0].ToString());
}

Datatable from Datagridview(databinding)

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!

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