can we use datagridview as datasource? - c#

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

Related

DataGridView c#, making a new a custom "fill" method

I have a table on the db, which is shown on 2 different datagridviews, but, one is filled by default, showing all the data on the table, and the second one I want to be filled with a condition.
So I'd like to fill that table initialy with a custom select query. How can I achieve that?
pd: I use datasets, in which I created the custom query, so the question should be how do I fill by default a table with certain tableadapter I made.
if you can share your codes, you will find a most right answer quickly.
var query = db.table.Where(x=>x.column1==condition1).ToList();
dataGridView1.DataSource = query (); dataGridView1.DataBind();
Or, if you have filled datatable/dataset you can write
dataGridView1.DataSource = yourDataTable; dataGridView1.DataBind();
You want to filter the data in your DataSet then set the DataSource of your DataGridView to a DataTable created by that filter. The code would look something like:
// Need to create a DataView from your original DataSet
// and set the view to the default view from your DataSet.
DataView view = new DataView();
view = myDataSet.Tables[0].DefaultView;
// Next, create a filter on that view
view.RowFilter = "State = 'CA'";
// Now create a DataTable from the view
// and set the DataSource of the DataGridView to that DataTable.
DataTable dt = view.ToTable("tablename");
dgrdToDisplay.DataSource = dt;

Fill DataGridView on condition from database

I have MySQL database and a DataGridView in C# and to fill the DataGridView I do the following:
schoolDataSet schl = new schoolDataSet();
schoolDataSetTableAdapters.studentinfoTableAdapter adptr = new schoolDataSetTableAdapters.studentinfoTableAdapter();
adptr.Fill(schl.studentinfo);
dataGridView1.DataSource = schl.studentinfo.DefaultView;
and undesired columns I make them visible = false from DataGridView properties but I came with a problem if I want to specify what data (rows) to fill in DataGridView such applying a where condition like:
fill data in DataGridView WHERE IsActive = 1 so can I still use the above code with some modifications or I have to write SQL query and fill the DataGridView manually ?
After searching and trying tons of codes I got it as following in simplest code:
In the code above just comment out last line which is dataGridView1.DataSource = schl.studentinfo.DefaultView; or simply replace it with the following
DataView dv = new DataView(schoolDataSet.studentinfo, "IsActive = 'false'", "id", DataViewRowState.CurrentRows);
Which creates a new DataView and filters according to IsActive column with false value, the third parameter id is to sort based-on, and finally you can write another line
dataGridView1.DataSource = dv; that will tell the DataGridView to load data from DataView.
Hope to save someone's time.
Big thanks goes to #Karthik Ganesan

How to update DataGridView after using SetOrdinal() on a column

I have a DataGridView whose DataSource is bound to a DataView with a table bound to it. If need to be able to insert columns into the table so I just do this:
DataView.Table.Columns.Add(newColumn);
DataView.Table.Columns[columnCount-1].SetOrdinal(desiredIndex);
Trouble is after doing so the DataGridView reflect the change unless I do something silly like this.
DataView.Table = new DataTable("tempTable");
DataView.Table = orginalTable;
Wondering how to properly get the DataGridView to see the index change and redraw itself?
Update() and Refresh() did not work for me.
So I decided to go the following way:
var temp = dataGridView1.DataSource;
dataGridView1.DataSource = null;
dataGridView1.DataSource = temp;

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 can I clear rows in DataGridView with C#?

Following Error in this line.
datagridview1.Rows.Clear()
but this line gives error:
Cannot clear this list.
I also had similiar problem when I try to clear DataSource of a DataGridView after I had binded it to a DataTable with:
DataTable DT = ... ; // fill it
datagridview1.DataSource = DT;
when I try to clear it's rows later with the following code:
datagridview1.DataSource = null
I get this error:
ERROR: Object reference not set to an instance of an object
This object reference ERROR problem already solved in here. But I managed to solve my own problem (clearing DataGridView rows) with this code:
DataTable DT = (DataTable)datagridview1.DataSource;
if (DT != null)
DT.Clear();
I know that this question was asked a very long time ago, but I hope my solution would solve someone problems.
Is your DataGridView bound to a DataSource, i think thats why its not allowing you to clear it since its bound to an underlying DataTable or List.
you could try setting the DataSource Property to null
datagridview1.DataSource = null; for clearing
private void button_Limpar_Click(object sender, EventArgs e)
{
DataTable DT = (DataTable)dataGridView_Cidade.DataSource;
if (DT != null)
DT.Clear();
}
#endregion
Simply add this line at beginning of your event:
dgv_nameOfGridView.DataSource=false;
Now every time you click it will erase the dgv..
You have to Clear datasource not datagridview rows.
datagridview1.DataSource = null;
Another way is
1) Dont assign direct datasource to gridview.
add rows from datatable to gridview
foreach (DataRow row in dataTable.Rows)
{
var dataGridRow = new DataGridViewRow();
dataGridRow.CreateCells(datagridview1);
for (int i = 0; i < row.ItemArray.Length; i++)
{
dataGridRow.Cells[i].Value = row.ItemArray[i];
}
datagridview1.Rows.Add(dataGridRow);
}
then use
datagridview1.Rows.Clear()
You can use this simple method:
First clear your DataTable and then refresh your DataGridView
dataTable.Clear();
dataGridView.Refresh();
Hope this help
Easy solution is to clear the DataSet.
ds.Clear();
Since you are using a bound grid, have you tried to call your loading
function twice and verified that the data is not doubling?
Since it is bound, loading twice ought to not duplicate the data.
http://www.vbforums.com/showpost.php?s=aa5f116586c00a2d9ea15e3727fc5c2f&p=2841192&postcount=9
First clear DataSource and then clear DataGridView
in VB
datagridview1.DataSource = Nothing
datagridview1.Rows.Clear()
hope help
If you load your DataGridView with a parameter, you can send an empty parameter to it. This will clear your DataGridView without having to set its DataSet to null.
For example, I load my DataGridView with a Code, when I fill a TextBox.
this.dataTable1TableAdapter.Fill(this.ds_MyDataSet.DataTable1, TextBox1.Text);
If I want to clear its content, then
this.dataTable1TableAdapter.Fill(this.ds_MyDataSet.DataTable1, "");
Here we are 8 years later.
Although
datagridview1.DataSource = null;
is a satisfactory answer for most, for me this removes all customizations I've added to the columns in design view. So hidden columns appears if I want to clear out the rows.
So rather than clear out rows:
datagridview1.Rows.Clear()
Clear out the DataTable or DataView that you used to set up the DataGridView. Note you don't have to check if something is null nor worry about Object not set to reference errors.
So here's how I did mine:
//Populate the datagridview
DataTable _DT = new DataTable();
BindingSource _BS = new BindingSource();
//Initially fill up your datatable with stuff
//You can call this method again if data needed to be changed
public void fillDT(int id) {
_DT = fillUpDataTableWithStuffFromDB(id);
_BS.DataSource = _DT.DefaultView;
datagridview1.DataSource = _BS;
_BS.ResetBindings(false);
}
//You can use this method to mimic the functionality above
//But rather fetching data, just clear out the datatable and pass it in
public void clearDT() {
_DT.Clear();
datagridview1.DataSource = _DT.DefaultView;
datagridview1.Refresh();
}
As you can see above, I just cleared out the datatable, and passed that into the datagrid. This kept all my properties I set on the datagridview column.
foreach (DataGridViewRow item in this.datagridview.Rows)
{
datagridview.Rows.RemoveAt(item.Index);
}
I had the same problem I tried with many solutions.
In the end I realized that we can't clear the DataGridView if we use it's property "DGV.Datasource" because DGV takes its data from the dataset so you need to clear the DataTable rows
Dataset.Tables["TableName"].Rows.Clear();
If you use this function in the Load of the Form you need to add a condition
if (DataSet.Tables["TableName"] !=null)
Dataset.Tables["TableName"].Rows.Clear();
or you will get this error
Object reference not set to an instance of an object.

Categories

Resources