I am trying to find value from dataview using column name. My dataset shows value but my if condition returns false. I am working in asp.net using c#.
I have tried with different code. I am trying to get value like this
dv[0].DataView.Table.Columns[0].ToString().Contains("52")
//RETURN FALSE
OR
dv[0].Equals("52")
// //RETURN FALSE
OR
dv[0].Find("52")
// //RETURN FALSE
Following is my dataset
You can access the DataRow that is exposed by the DataRowView by using the Row property of the DataRowView. When you view values by using a DataRowView, the RowStateFilter property of the DataView determines which row version of the underlying DataRow is exposed.
Which activity can be used to retrieve the value from a specific column, from a DataRow object? Get Row Item!
The DataView provides several ways of sorting and filtering data in a DataTable: You can use the Sort property to specify single or multiple column sort orders and include ASC (ascending) and DESC (descending) parameters.
You can get the column names from DataRow by using (datarow). Table. Columns and this will return “DataColumnCollection”.
If "GBA_Nbr_GBAccount" column is a string type, it may contains spaces. You should trim text before comparing. Try this
dv[0]["GBA_Nbr_GBAccount"].ToString().Trim().Equals("52");
You could use Linq
to query the datatable or the dataview. For example, assuming your column is of type string:
var condition = yourDataTable.AsEnumerable()
.Any(r => r.Field<string>("GBA_Nbr_GBAccount") == "52");
var condition = yourDataView.Cast<DataRowView>()
.Any(rv => rv.Row.Field<string>("GBA_Nbr_GBAccount") == "52");
If the column was an integer, just change the Field<string>
to Field<int>
and compare against an integer, not a string
var condition = yourDataTable.AsEnumerable()
.Any(r => r.Field<int>("GBA_Nbr_GBAccount") == 52);
var condition = yourDataView.Cast<DataRowView>()
.Any(rv => rv.Row.Field<int>("GBA_Nbr_GBAccount") == 52);
Example application using string column:
static void Main(string[] args)
{
DataSet dataset = new DataSet();
dataset.Tables.Add(new DataTable("table1"));
dataset.Tables[0].Columns.Add(new DataColumn("Value", typeof(string)));
dataset.Tables[0].Rows.Add("10");
dataset.Tables[0].Rows.Add("52");
DataTable table = dataset.Tables[0];
DataView view = table.DefaultView;
var condition1 = table.AsEnumerable().Any(r => r.Field<string>("Value") == "52");
var condition2 = view.Cast<DataRowView>().Any(rv => rv.Row.Field<string>("Value") == "52");
Console.WriteLine(String.Format("Result querying datatable: '{0}'. Result using dataview:'{1}'", condition1, condition2));
Console.ReadLine();
}
If you are really using a string for the column, check for white spaces and apply a trim if needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With