Change a gridview's datasource dynamically - c#

I have two DataTable's which I want to use as DataSoure for a GridView. And when an user clicks on a button1 I need to load the first table and the user clicks button2 the second table should be loaded. My current problem is that the tables don't have the same structure (one has more columns) and when the user clicks button1 first and after clicks button2 the second table is loaded with the right values but it shows the extra columns from table1 as well.
What's the easiest way to fix this?

Instead of manually adding columns set the property DataGridView.AutoGenerateColumns to true. This will cause the grid to create columns according to the data source.

To expand a bit on the Habib answer:
private void LoadTables()
{
// Mock the tables data
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
// Clear data from gridview
GridView1.DataSource = null;
GridView1.DataBind();
// Load first table
GridView1.DataSource = dt1;
GridView1.DataBind();
// Clear data from gridview
GridView1.DataSource = null;
GridView1.DataBind();
// Load second table
GridView1.DataSource = dt2;
GridView1.DataBind();
}

Related

Datatable values to datagridview, only showing one columns data

I have a datatable filled with a report from a web service. I am now trying to display the datatable in an datagridview. This is the code I use to build the datatable:
// Create DataTabe to handle the output
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("EmployeeFirstName");
dt.Columns.Add("EmployeeLastName");
dt.Columns.Add("DepartmentName");
dt.Columns.Add("DepartmentCode");
dt.Columns.Add("LocationName");
dt.Columns.Add("DivisionCode");
dt.Columns.Add("EarningName");
dt.Columns.Add("OTHours");
dt.Columns.Add("WorkDate")
Fill the new datatable:
foreach (ReportRow row in report.Rows)
{
dt.Rows.Add(string.Join(",", row.ColumnValues));
}
Then I try to bind the data in the datatable to the dataGridview:
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
When I run the application it only displays the data from the first column in the datatable. Do I need a loop of sorts to work through the columns or am I just missing a step?
Yes that's cause you are adding only one value to your dt when you say dt.Rows.Add(string.Join(",", row.ColumnValues));. You should be doing something like below (assuming that ReportRow also has the columns with same names like "EmployeeFirstName" else change the names accordingly)
foreach (ReportRow row in report.Rows)
{
DataRow dr = dt.NewRow();
dr["EmployeeFirstName"] = row["EmployeeFirstName"];
dr["EmployeeLastName"] = row["EmployeeLastName"];
dr["DepartmentName"] = row["DepartmentName"];
//rest of the columns fill
//once all columns filled
dt.Rows.Add(dr);
}
dt.Rows.Add(string.Join(",", row.ColumnValues)); -> You can either add a single DataRow item or a array of objects.
From your call, you chose the later, you are adding a array of objects, except you are adding ONE SINGLE object.
string.Join(",", row.ColumnValues) is one object.
Well after sleeping I have found the issue with dropping it into an sql table... I didn't take into account that the export to a CSV and the addition of the " , " would affect the export to sql. Here is the modification of the lines of code that was the issue:
foreach (ReportRow row in report.Rows)
{
dt.Rows.Add(row.ColumnValues);
}
Thank you all for your responses!

How to create and attach rows to this DataGridView?

I'm beginner in .Net ,so maybe my question will seem naive to some of you.
I have DataGridView table in WinForm project:
It contain three columns(image,combobox and textBox columns).
Any idea how to create and attach rows to this table?
Thank you in advance!
You create a data source, then bind the data source to the grid's DataSource property. You then add a record to your data source.
// create data source
BindingList<Shape> dataSource = new BindingList<Shape>();
// add record to data source
dataSource.Add(new Shape("Some Contour", "Circle", "Some Name"));
// bind data source
yourDataGridView.DataSource = typeof(BindingList<Shape>);
yourDataGridView.DataSource = dataSource;
Set the DataPropertyName of each column to matches the names of the fields in your Shape class.
DataGridViewTextBoxColumn colName = new DataGridViewTextBoxColumn();
colName.DataPropertyName = "Name";
yourDataGridView.Columns.Add(colName );
However, I recommend you use Virtual Mode instead to keep your data separate and decoupled.
If you wish to accept inputs from user, you have to create a form on this page using which the user can provide inputs. Take those values and add them to a DataTable. Following is a sample snippet showing it:
DataTable dt = new DataTable();
dt.Columns.Add("Contour",typeof(string)); //I am assuming that you will store path
//of image in the DataTable
dt.Columns.Add("Shape",typeof(string));
dt.Columns.Add("Name",typeof(string));
Keep adding new rows to the DataTable as you receive inputs from the user:
DataRow row = dt.NewRow();
row["Contour"] = txtContourPath.Text;
row["Shape"] = ddlShape.SelectedValue;
row["Name"] = txtName.Text;
dt.Rows.Add(row);
Assign above DataTable to DataSource property of the GridView.
dgv.DataSource = dt;
You can use method:
dataGridView1.Rows.Insert(...)
dataGridView1.Rows.Add(...)
Jay's answer : use dataGridView1.DataSource = dataSource;
Hope I can help you.

C# DataGridView data-bound error with Grid.Rows.Add method

i have a DataGridView on the Form. I select some data from database and load them to datatable and after that i make reference this datatable to grid's datasorurce as below.
string sql = "";
sql = "SELECT id,name,surname,code FROM t_persons";
DataTable dt = new DataTable();
...
adapter.Fill(dt);
grid.DataSource = dt;
and after that i want to add new row to this grid with grid.Rows.Add() method. But every time it gives an error Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.
So whatis the problem and how can i solve it.
You should add row to the DataTable, not to the DataGridView. That is what the exception is saying. Try:
DataRow newRow = dt.NewRow();
dt.Rows.Add(newRow);
Please you can add row directly to datatable and it's effect on gridview because it's bind to datatable.

DataGridView doesn't show data after clone rows

Windows form application. C# 4.0.
Basically I have two datagridviews dgv1 and dgv2. One displays the table correctly. I want to select and clone some rows from dgv1 to dgv2 by clicking on the cells in dgv1.
But the second one doesn't show data at all.
DataTable dt = new DataTable();
dgv2.AutoGenerateColumns = true;
private void btnAdd_Click(object sender, EventArgs e)
{
DataRowView currentDataRowView = (DataRowView)dgv1.CurrentRow.DataBoundItem;
DataRow row = currentDataRowView.Row;
// add row
dt.ImportRow(row);
dgv2.DataSource = dt;
}
In debug mode, what I found is that
?dt.Rows.Count
1
?dt.Columns.Count
0
?dgv2.AutoGenerateColumns
true
Thanks for advice.
You must create your columns or copy the schema from another table!
instantiate dt by cloning the datasource of dgv1, ie:
datatable dt = otherdatatable.clone()
where otherdatatable is the datatable datasource of dgv1

Can't update data in datagridview

Goal:
Having two buttons that should be enable to add or delete data from datagridview. The changes should be make in real time so you should be see the new result.
Problem:
Having problem to display the new result after I have used button add functionality because the result won't display in real time. In order to view the result I have to close and reopen the application in order to view the new result.
Please remember that I don't use a database.
I'm using class table and then I connect the table to the datagridview's datasource.
DataTable table = new DataTable();
table.Columns.Add("a");
table.Columns.Add("b");
foreach (var a in myManagerProduct.GetAllProductList())
{
DataRow row;
row = table.NewRow();
row["a"] = a._articleNumber;
row["b"] = a._name;
dgridStock.Rows.Add(row);
table.Rows.Add(row);
}
dgridStock.DataSource = table;
Try following code snippet to add new row to the grid.
DataView dv = ((dgridStock.BindingContext[dgridStock.DataSource] as CurrencyManager).List as DataView);
DataRowView rowView = dv.AddNew();
rowView["a"] = a._articleNumber;
rowView["b"] = a._name;
rowView.EndEdit();
And make sure dgridStock.DataSource = table; is set only once. After that every addition shouldn't refresh the DataSource property.
As Sanjeevakumar Hiremath said, don't forget EndEdit() command for row or DataTable in general. After finishing all the operations about inserting, updating and deleting data, call DataGridView.Refresh().

Categories