How to Bind DataTable to DataGridView - c#

I am trying to bind DataTable to DataGridView as below;
DataTable table = new DataTable();
foreach (ConsumerProduct c in ctx.ConsumerProducts)
{
DataRow row = table.NewRow();
row["Id"] = c.ID;
row["Model"] = c.Model;
row["Status"] = "Offline";
table.Rows.Add(row);
}
dataGridView1.DataSource = table;
I get exception at the first line itself row["Id"]
Column 'Id' does not belong to table .
P.S. I have already added these columns in the designer view of dataGridView.

You just created a blank DataTable and then you are trying to add data to particular columns like Id, Model and Status.
You have to add those columns as well.
DataTable table = new DataTable();
table.Columns.Add("Id");
table.Columns.Add("Model");
table.Columns.Add("Status", typeof(string)); //with type
There is no issue in biding.
Also you can project your required column to an Anonymous type and then bind that to your data grid like:
var result = ctx.ConsumerProducts
.Select(r=> new
{
Id = r.ID,
Model = r.Model,
Status = "Offline"
}).ToList();
dataGridView1.DataSource = result;

Related

DataGridView.DataSource not working when defining columns from code

I want to define the columns of my DataGridView manually from code. Something like this:
int index = 0;
string columnName = "something";
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.Name = columnName;
column.HeaderText = columnName;
myDataGridView.Columns.Insert(index++, column);
And then I bind the DataGridView.DataSource to a DataTable:
myDataGridView.DataSource = null;
table = new DataTable();
table = dbAccess.GetDataFromDB(); //This function returns a DataTable filled with data
myDataGridView.DataSource = table;
I already checked that after executing GetDataFromDB table is filled with data, but when binding it to DataSource, the DataGridView keeps all its row empty (although it creates as many rows as there are on the table).
Some code that I'm missing here?

Filtering Items from DataGridview to a DataTable produces Invalid Results

I have the following datagridview.
I need to filter and save rows separately that match Valid and Invalid property of the status column.
It do not have a datasource.So i'm creating a DataTable,filtering it and saving the results.But the filtering is not working as intended and contains results that does not match the expression
DataTable dt = new DataTable();
//Populating Virtual Table
foreach (DataGridViewColumn col in dataGridView4.Columns)
{
dt.Columns.Add(col.Name);
}
foreach (DataGridViewRow row in dataGridView4.Rows)
{
DataRow dRow = dt.NewRow();
foreach (DataGridViewCell cell in row.Cells)
{
dRow[cell.ColumnIndex] = cell.Value;
}
dt.Rows.Add(dRow);
}
Now creating a Filtered Table containing results where column named Status equals "Valid"
filtered = dt.Copy();
DataTable filteredResults = new DataTable();
DataTable filteredResults2 = new DataTable();
// filtered.Columns.Remove("Status");
var expression = string.Format("Status LIKE '%{0}%'", "Valid");
if (filtered.Select(expression).Any())
{
filteredResults = filtered.Select(expression).CopyToDataTable();
}
But the filtered data table contains elements which has the Status column value "Invalid".What i'm i doing wrong ? Please advice.
You are using LIKE in your expression. LIKE checks to see if the value contains the specified value. Use = instead.

Data not showing up in the gridview

I have two gridviews in my asp.net page. Where the datas are coming from two different databases. In that, one gridview has select row function. Now what I want to do is, I need to generate my 3rd gridview row by row according to the selection of the 1st gridview's 2 cell and the 2nd gridview 1st column data(1st column data is common for all the rows).
This is my code:
DataTable dt = new DataTable();
var EmpID = (Label)grdEmp.SelectedRow.Cells[1].FindControl("lblEmpID");
var firstName = (Label)grdEmp.SelectedRow.Cells[1].FindControl("lblFirstName");
var date = DateTime.Now.ToString();
var planID = (Label)grdPlanID.Rows[0].Cells[1].FindControl("lblPlanID");
string empid = Convert.ToString(EmpID.Text);
string first = Convert.ToString(firstName.Text);
string Date = Convert.ToString(date);
string planid = Convert.ToString(planID.Text);
dt.Columns.Add("Emp_ID", typeof(string));
dt.Columns.Add("First_Name", typeof(string));
dt.Columns.Add("Created_Time", typeof(string));
dt.Columns.Add("Plan_ID", typeof(string));
DataRow dtrow = dt.NewRow(); // Create New Row
dtrow["Emp_ID"] = empid; //Bind Data to Columns
dtrow["First_Name"] = first;
dtrow["Created_Time"] = Date;
dtrow["Plan_ID"] = planid;
dt.Rows.Add(dtrow);
grdList.DataSource = dt;
grdList.DataBind();

How to check if a record is already present in the DataView? C#

I have a DataView which has two columns: ContactID, and Name
How can I check if a particular ContactID is already existing in the DataView?
Have you had a look at DataView.FindRows Method or maybe DataView.Find Method
The DataView has a method called FindRows, this can be used to search for a specific contactID, for example...
var table = new DataTable();
var column = new DataColumn("Id", typeof (int));
table.Columns.Add(column);
table.PrimaryKey = new[] {column}; // Unique Constraint
var row = table.NewRow();
row["Id"] = 100;
table.Rows.Add(row);
row = table.NewRow();
row["Id"] = 200;
table.Rows.Add(row);
var view = new DataView(table) { ApplyDefaultSort = true };
var rows = view.FindRows(200);
foreach(var r in rows)
{
Console.WriteLine(r["Id"]);
}
Use the Following code to Find the row in the Dataview
//Your original Table Which consist of Data
DataTable dtProducts = new DataTable();
//Add the DataTable to DataView
DataView ProductDataView = new DataView(dtProducts);
ProductDataView.RowFilter = "";
ProductDataView.Sort = "ProdId";
int recordIndex = -1;
//In the Find Row Method pass the Column
//value which you want to find
recordIndex = ProductDataView.Find(1);
if (recordIndex > -1)
{
Console.WriteLine("Row Found");
}

Adding a comboBox to a gridview in WinForms

I am trying to create a gridview with a string column, a checkbox column, and a dropdownlist/combobox column. The first two are finished (all code behind), just need help with the last one.
DataTable dt = new DataTable("tblAir");
dt.Columns.Add("Flight Details", typeof(string));
dt.Columns.Add("Prefered Seating", typeof(bool));
//doesn't work
dt.Columns.Add("Add Remark", typeof(ComboBox));
The data for the combobox is being supplied on load as we cannot work with a database.
Peter Bromberg has a detailed article on creating a Winforms gridview with comboboxes:
http://www.eggheadcafe.com/articles/20060202.asp
DataAccessLayer dal = new DataAccessLayer();
DataTable movies = dal.GetMovies();
gvMovies.DataSource = movies;
gvMovies.AllowUserToAddRows = false;
gvMovies.AllowUserToDeleteRows = false;
//Create the new combobox column and set it's DataSource to a DataTable
DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.DataSource = dal.GetMovieTypes(); ;
col.ValueMember = "MovieTypeID";
col.DisplayMember = "MovieType";
col.DataPropertyName = "MovieTypeID";
//Add your new combobox column to the gridview
gvMovies.Columns.Add(col);

Categories