find and display datarows in datagridview - c#

I faced to issue of displaying datarows from DataTable from DataSet. I used a temporary table. I found rows that I need by id and copy it to temporary table and then diplay in DataGridView. Is there any way to find and display rows that I need in DataGridView directly from DataTable from DataSet without using any temporary DataTable's? I've tried to do this by hiding and unhiding rows in DataGridView, but sadly it didn't worked out
private DataTable tblFiltered =
ds.Tables("GRAPHICS").AsEnumerable().Where(row =>
row.Field<int>("GRAPHIC_ID") == graphId && row.Field<int>
("GRAPHIC_ID")).CopyToDataTable;

Assuming that DataSet 'ds' containing Table 'GRAPHICS',We can use DataView to Display filtered records in DataGridView. Ex.
int graphId = 2; //Assuming
DataView dv = ds.Tables["GRAPHICS"].AsDataView();
dv.RowFilter = "GRAPHIC_ID = " + graphId; //RowFilter :: Expression used to filter which rows are viewed !!
dataGridView.DataSource = dv.ToTable();

You can use filter
(DatagridView.DataSource as DataTable).DefaultView.RowFilter = string.Format("GRAPHIC_ID= '{0}'", graphId);

Related

How to hide particular data row in a datatable without deleting it?

I want to hide a data row without deleting it in c# or vb.net. Please help me with this.
I want to hide a data row without deleting it in c# or vb.net.
ResultSelection.Checked = False ' Checkbox
Dim Dt As DataTable
Dim dr as datarow
Private SBind As BindingSource = New BindingSource()
With Dt
.Columns.Add(" Name", GetType(String))
.Columns.Add("Age" , GetType(integer))
.Columns.Add("Marks" , GetType(integer))
dr(0) = ( "Mark",19,99)
dr(1) = ( "Rahul",20,35)
dr(2) = ( "Steve",19,50)
SBind.DataSource = Dt
DatargridView.DataSource = SBind
if ResultSelection.Checked = False then
"entire row dr(2) should not be visible
else
"entire data table should be visible along with dr(2)
end if
You can't hide rows in a DataTable but you can in a DataView. Every DataTable has a DataView associated with it by default, in its DefaultView property. When you bind a DataTable, it is actually the DefaultView that the data comes from. As such, you can set the RowFilter of that DataView in order to hide rows that don't match certain criteria. For instance, if you had a Sex column that contained "Male" or "Female", you could hide all the "Male" rows like this:
myDataTable.DefaultView.RowFilter = "Sex = 'Female'"
Any controls bound to that DataTable would not see the "Male" rows and you could loop through the DataView code to see the filtered data too.
If you are binding, I would recommend using a BindingSource in between, in which case you set its Filter property in the same way.

Correct way of filtering datagrid using datatables in C# WPF

I am creating a WPF application. There is a DataGrid displaying my items and search bar to filter the data. As you know we can't have specific rows from a Dataable to be referenced from another datatable. So the way I'm filtering right now is cloning my original database and adding the rows which matches search bar text to the cloned datatable. After that setting the datagrid's ItemsSource to the cloned datatable to show the filtered rows.
Now the problem is that when I edit my datagrid with filtered rows then obviously that cloned datatable is being modified not the original datatable. So how can I make those changes in the original datatable as well ?
I tried referencing rows from original datatable but that's no possible as one DataRow in memory can have only one container, the original datatable in this case.
EDIT
The answer was simple instead of using 2 DataTable use a DataView which is designed for this very purpose. See the modified code below.
My filter logic:
var filteredTable = dt.Clone();
foreach( DataRow row in dt.Rows)
{
if(row[FilterCategory].ToString().StartsWith(txtb_search.Text))
{
filteredTable.Rows.Add(row.ItemArray);
}
}
ItemsGrid.ItemsSource = filteredTable.DefaultView;
Here is how to do filtering the correct way using DataView. The filter string can have many forms depending on the requirement. sortColumn is filterColumn right now but can be any column to base sort on. Here is a quick tutorial to all this: http://www.csharp-examples.net/dataview-rowfilter/
string filterColumn = dt.Columns[columnIndex].ToString();
string filter = filterColumn + " LIKE '" + txtb_search.Text + "*'";
DataView dv = new DataView(dt, filter, sortColumn , DataViewRowState.CurrentRows);
ItemsGrid.ItemsSource = dv;

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!

Add few records to gridview from DataTable

I have been working on asp.net/C# project. I could bind the DataTable to gridview. But i have a situation where i don't want to bind all the records in DataTable. is there any method to bind only few records to gridview? any Alternatives to GridView.DataBind()?
Thank you
try this,
using datatable select query you can achieve this,
for example,
DataTable dt=yourdata;
DataRow[] dr=dt.Select("columnname='Maths'");
foreach (DataRow row in dr) {
dt.ImportRow(row);
}
GridView1.DataSource=dt;
GridView1.DataBind();
where Maths = your search criteria.
You can add the rows manually, i.e. without using a data source.
var newRowIndex = dataGridView1.Rows.Add(firstValue, secondValue, thirdValue);
You might use it like this:
foreach (System.Data.DataRow row in myDataTable.Rows)
{
if(meets my criteria...)
{
dataGridView1.Rows.Add(row["Column1"], row["Column2"], row["Column3"]);
}
}
In fact, this may be a better solution as it allows you to sort columns easily in the UI whereas binding to a data source does not allow that.
Use DataView for the DataTable, So that you can able to filter records and assign the dataview to Grid.
for example:
DataView dv = new DataView(DataTable, "Column1=Value", "Column2", DataViewRowState.CurrentRows);

DataView.Count different DataView.Table.Rows.Count

I am using C# and .NET 3.5 and have a GridView that I am setting the dataSource programatically in the code-behind page. I have data in a DataTable and then depending on a column value (isValid boolean) of each Row, I create a new row using DataRowView.AddNew() method into 1 of 2 DataViews - dvValid or dvInvalid. I am NOT creating a new DataTable.NewRow to add to the DataView Table. Then I bind the GridView to the appropriate dataView.
There is a problem when I am sorting the GridView. I am having a problem with 1 row not being sorted correctly, all other rows are sorted fine. I debugged my code and found that the DataView.Count is 1 more than the DataView.Table.Rows.Count even though I am calling DataView.Table.AcceptChanges() method. This is strange since the dataTable should have all committed rows and therefore the counts should be the same.
So why are the 2 counts different? A DataView is a subset of the DataTable so should it not have equal or less rows than the DataTable.
When I populate the DataView, should I first create the DataTables rather than creating the DataView directly? Right now, I am directly creating a DataRowView without a dDataTableRow, is this the correct approach?
Thanks for your help.
Code snippet : C#
...
//get the data as DataTable
members = GetMemberDataTable ();
//create views from a new DataTable with no rows
dvValidMembers = new DataView (CreateMembersDT("ValidMembers"));
dvInValidMembers = new DataView (CreateMembersDT("InvalidMembers"));
//iterate thru each row and put into appropriate DataView
foreach (DataRow memberRow in members.Rows)
{
if ((bool)memberRow["isValid"])
//Add to valid members Dview
member = dvValidMembers.AddNew();
else
//add to InValid members Dview
member = dvInvalidMembers.AddNew();
member["memberID"] = memberRow["memID"];
} //foreach
dvInvalidMembers.Table.AcceptChanges();
dvValidMembers.Table.AcceptChanges();
}
private System.Data.DataTable CreateMembersDT ( string tableName)
{
System.Data.DataTable dtMembers = new System.Data.DataTable(tableName);
dtMembers.Columns.Add(new DataColumn("memID", typeof(int)));
return dtMembers;
}
That 1 row that isn't sorting right, could that be the last row?
I think you are missing a DataView.EndEdit():
foreach (DataRow memberRow in members.Rows)
{
DataView dv;
if (...)
//Add to valid members Dview
dv = dvValidMembers;
else
dv = dvInvalidMembers;
member = dv.Addnew();
member["memberID"] = memberRow["memID"];
dv.EndEdit();
}
But I would also like to note that you could probably use 2 Views with a Filter on isValid and then you would only need to point them to the original members table.

Categories