DataSource to ListItemCollection - c#

I'm looking for a way how is it bound that data from DataSource can be accessed via Item property on ListControl Class.
Can anyone give me an example how properties from passed object to DataSource are bound to generic class ListItemCollection? How that translation can be done by a code?
The translation I'd like to see is from DataSet to ListItemCollection. Thanks in advance for any help.

// Setting up a dataset. This dataset has no data; in real life you'd get the
// data from somewhere else, such as a database, and wouldn't need to build it.
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("ID"));
dt.Columns.Add(new DataColumn("Description"));
ds.Tables.Add(dt);
// Creating a list box. You'd probably have this declared in your HTML and wouldn't need to
// create it.
ListBox listBox1 = new ListBox();
listBox1.DataSource = ds.Tables[0];
listBox1.DataValueField = "ID";
listBox1.DataTextField = "Description";
listBox1.DataBind();
If your question is about how the binding is done behind the scenes, that has a fairly complex answer.

Related

DataGridView DataSource Not Updating

I am using Winforms DevExpress and I am binding a DataTable to a DataGridView which is working fine. The problem I am having is that I have some functions that will build a new DataTable object which is separate from the original which needs to replace the original DataTable that is bound to the DataGridView.
DataTable originalTable = new DataTable("OriginalTable");
//Populate originalTable
myDataGridControl.DataSource = originalTable;
Everything works fine with the code above, but the following code creates a new DataTable and needs to be set as the DataSource for myDataGridControl.
DataTable newTable = new DataTable("NewTable");
//Populate newTable
//Set newTable as the DataSource for myDataGridControl
myDataGridControl.DataSource = newTable;
I have tried several different attempts to make this work such as calling RefreshDataSource(), Refresh(), setting DataSource to null. I have not gotten it to work yet. How do I do this?
Try using a BindingSource, like this:
DataTable sourceTable = new DataTable("OriginalTable");
BindingSource source = new BindingSource();
source.DataSource = sourceTable;
myDataGridControl.Datasource = source;
Now when you want to re-bind, update the sourceTable variable, like this:
sourceTable = new DataTable("NewTable");
// If the structure of `OriginalTable` and `NewTable` are the same, then do this:
source.ResetBindings(false);
// If the structure of `OriginalTable` and `NewTable` are different, then do this:
source.ResetBindinds(true);
Note: Read BindingSource.ResetBindings Method for more information about ResetBindings().
Having you tried the following combination?:
myDataGridControl.DataSource = originalTable;
myDataGridControl.DataSource = null;
myDataGridControl.DataSource = newTable;
In my experience, setting the DataSource to null then to the second source does the trick.
In case anybody is having trouble even after trying the other suggestions, the following call to PopulateColumns() on the GridControl.MainView property solved the problem for me.
For example:
myDataGridControl.MainView.PopulateColumns();
This can also be referenced from the following article with DevExpress. http://www.devexpress.com/Support/Center/Question/Details/Q362978
Kinda old topic, but since it bugged me, I decided to share my experience...
Binding the source didn't work for me and Datagridview doesn't have "MainView" variable.
I suspect the issue happens, in my case, after running the sorting command:
MyDataTable.DefaultView.Sort = "Column Asc";
MyDataTable = MyDataTable.DefaultView.ToTable();
My solution was to rebind again after actions performed:
myDataGrid.DataSource = MyDataTable;

How to get an underlying DataTable from a control (i.e. under DataGridView)?

dataGridView1.DataSource = myDataSet1;
dataGridView1.DataMember = "SomeTable";
And now I want to get the refference to DataTable back from my dataGridView1.
Something like this:
DataTable dt = (DataTable)dataGridView1.DataSource... ;
I'm aware of BindingContext, but couldn't find the way to get DataTable refference back.
Got it.
DataSet dataSet = (DataSet)dataGridView1.DataSource;
string tableName = dataGridView1.DataMember;
DataTable dt =dataSet.Tables[tableName];
you are assigning Dataset as datasource to your gridview. So, the line below would help u.
DataTable dt = ((DataSet)dataGridView1.DataSource).Tables[index];
Assuming that you have only one datatable in your dataset. you can also use your table name instead of index.
You can convert it in this way
BindingSource bs = (BindingSource )dgrid.DataSource;
DataTable tCxC = (DataTable ) bs.DataSource
Look at this question How can I export a GridView.DataSource to a datatable or dataset?
You can either be resilient (to avoid null error) or take a chance.
The short version is:
DataTable dt = ((DataSet) dataGridView1.DataSource).Tables[0];
A more resilient approach (not assuming the view is bound to a DataSet):
DataSet ds = dataGridView1 as DataSet;
if (ds != null) DataTable dt = ds.Tables[0];
Obviously you can inspect/check the number of tables in the DataSet.

can we use datagridview as datasource?

I'm trying to set the dataGridView as a datasource of some other datagridview, but it is not working. Please help me.
this.dataGridView2.DataSource = this.dataGridView1;
No compiler error, but not working as well.
this.dataGridView2.DataSource = this.dataGridView1;
this will show no compile error because this.dataGridView2.DataSource is expecting a type of object and you are assigning an object to it, but no datasource assigned here , to do that
this.dataGridView2.DataSource = this.dataGridView1.DataSource
assign like this
to Solve the Problem of changing data in datagrid one while changing data on first one
Try this
DataTable dt = (DataTable)dataGridView1.DataSource;
dataGridView2.DataSource = dt.Copy();
#Nighil sounds close, I don't know if that worked for you but I would not recomend using dataGridView as a datasource, I suggest you should separate out the logic keeping data separate from user controls, also using a 'BindingSource' gives you one easy method for refreshing data;
Say we had a method called 'getTablefromDatasource()' which got the data to be displayed and returned a 'DataTable'
DataTable table = getTablefromDatasource();
BindingSource source = new BindingSource();
dataGridView1.DataSource = source;
dataGridView2.DataSource = source;
then you can refresh the data with:
source.ResetBindings(false);

Removing rows from dataGridView-using dataTable

I am trying to remove all the rows to reload them (I need to remove all rows) For some reason its not removing them from my datagridview (tho its not adding any extra either) nothing is happening. I have tried many different methods, I know I have done this in the past. (maybe because its end of the day)
Here is my code trying a whole bunch of removes
private void loadMSXGridView()
{
BindingSource bs = new BindingSource();
dgv.DataSource = null;
dgv.Refresh();
bs.DataSource = GetTable();
dgv.DataSource = bs;
dgv.Columns[0].Width = 391;
dgv.Columns[1].Width = 30;
}
private DataTable GetTable()
{
DataTable t = new DataTable();
t.Rows.Clear();
t.AcceptChanges();
t.Columns.Add("Accounting Line", typeof(string));
t.Columns.Add("#", typeof(string));
foreach (AMAPnr.RemarkElement re in AMAPnr._RemarkElements)
{
if (re.ElementID == "RM" && re.FreeFlow.StartsWith("*MS"))
{
DataGridViewCell gridCellText;
DataGridViewCell gridCellElement;
gridCellText = new DataGridViewTextBoxCell();
gridCellText.Value = re.FreeFlow;
gridCellElement = new DataGridViewTextBoxCell();
gridCellElement.Value = re.ElementNo.ToString();
t.Rows.Add(gridCellText.Value, gridCellElement.Value);
}
}
return t;
}
My delete button calls loadMSXGridView, I only need to refresh everything because the items in my datagridview are associated to an element number, which won't remain the same
Initially, you are data-binding:
dgv.DataSource = GetTable();
you should then continue data-binding; either tell the table to clear itself (and repopulate the data), or just assign a different data-table to dgv.DataSource.
In my limited data binding experience it is not easy to edit a data source. You should handle your data edits using one of the row binding or other events. However if you want to edit a datasource you basically have to clone the structure, then import the rows. So in this sense you should actually go back to your datasource and select exactly what you want.
However..
If you want to filter / edit your data here is how you can do it:
DataSet ds1 = [Your Data Source]
DataSet ds2 = new DataSet();
ds2 = ds1.Clone();
for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
{
if (ds1.Tables[0].Rows[i].ItemArray[0].ToString() != "SomeValue")
{
ds2.Tables[0].ImportRow(ds1.Tables[0].Rows[i]);
}
}
ds1 = ds2;
If you simply just want to add a different datatable as the datasource, then do:
datagridview.DataSource = datatable;
datagridview.Invalidate();
That should work, as I have just done the exact same thing on a project i'm working on at the minute :)
My fault, everything worked after running a throughough debug I found
The remarks elements were not being deleted, thus it was getting deleted by adding the same items back in. I remove the items from the RemarkElement section and it works, thanks for your help everyone!
I would suggest to set the DataSource of your DataGridView to a BindingSource and change the DataSource of the BindingSource instead:
var table1 = GetDataTable();
var bindingSource1 = new BindingSource(table1, null);
dataGridView1.DataSource = bindingSource1;
// after reload
var table2 = GetDataTable();
bindingSource1.DataSource = table2;
that solves most problems, since you don't have to worry about how your data is bound.

Creating a DataTable object with dummy data

I am trying to databind a DataTable to an accordion and I have found that If I retrieve the DataTable from a database using a table adapter it binds to the accordion perfectly however what I want to do is create a dummy table (for testing purposes if I don't have access to my database) the code to create the dummy table is below:
DataTable table2 = new DataTable("articletable");
table2.Columns.Add("articleID");
table2.Columns.Add("title");
table2.Columns.Add("content");
DataRow row = table2.NewRow();
row[0] = "1";
row[1] = "article name";
row[2] = "article contents go here";
table2.Rows.Add(row);
When I try to data bind that table however the accordion does not display. I can bind it to a gridview or detailsview but not the accordion.
After 4 hours of banging my head against the wall, I discovered that the DataSource field is VERY picky.
Here's my code:
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Branch");
dt.Columns.Add("Officer");
dt.Columns.Add("CustAcct");
dt.Columns.Add("Grade");
dt.Columns.Add("Rate");
dt.Columns.Add("OrigBal");
dt.Columns.Add("BookBal");
dt.Columns.Add("Available");
dt.Columns.Add("Effective");
dt.Columns.Add("Maturity");
dt.Columns.Add("Collateral");
dt.Columns.Add("LoanSource");
dt.Columns.Add("RBCCode");
dt.Rows.Add(new object[] { "James Bond, LLC", 120, "Garrison Neely", "123 3428749020", 35, "6.000", "$24,590", "$13,432",
"$12,659", "12/13/21", "1/30/27", 55, "ILS", "R"});
ds.Tables.Add(dt);
accReportData.DataSourceID = null;
accReportData.DataSource = ds.Tables[0].DefaultView;
accReportData.DataBind();
Turns out that the accordion only likes being bound to a dataset table's defaultview. I tried binding to just a DataTable (dt) and it failed. Even dt.DefaultView failed. Once I added it to a DataSet, it binds like a champ. Very annoying, with lost of wasted time. I know you've probably long-since forgotten this, but I wanted to make it available to future searchers. Accordion.DataSource must be bound to a DataSet.Table.DefaultView to work.
Make sure you specify a type for the columns in the table2.Columns.Add(...)
Also, as seen in the answer below:
https://stackoverflow.com/a/6108163/637903
You can bind the Accordion Control to a DataTableReader constructed from the original DataTable
accReportData.DataSource = new System.Data.DataTableReader(ds.Tables[0]);
accReportData.DataBind();

Categories

Resources