I have the following method which returns dataset. I am using .NET 2.0
DataSet ds = GetAllRecords();
I want to get values from each column for a particular row and bind it to a variable.
How can this be achieved?
currently the method returns all the row from the table and I have to find that particular row based on ID.
However, if that is not possible I can come with
DataSet ds = GetSpecificRecord(id);
But I still need to get values from each column and bind it to variable.
Please advice.
// Create a table
DataTable table = new DataTable("users");
table.Columns.Add(new DataColumn("Id", typeof(int)));
table.Columns.Add(new DataColumn("Name", typeof(string)));
table.Rows.Add(1, "abc");
table.Rows.Add(2, "ddd");
table.Rows.Add(3, "fff");
table.Rows.Add(4, "hhh d");
table.Rows.Add(5, "hkf ds");
// Search for given id e.g here 1
DataRow[] result = table.Select("Id = 1"); // this will return one row for above data
foreach (DataRow row in result)
{
Console.WriteLine("{0}, {1}", row[0], row[1]);
}
This will get you the value from Row 0 obviously you would need to modify for multiple rows returned
long id = ds.Tables[0].Rows[0].Field<long>("ID");
You can do this with LINQ.
DataRow resultRow = ds.Tables["SomeTable"].AsEnumerable().Where(row => row.Field<int>("SomeID") == 1).FirstOrDefault();
For .NET 2.0 and below
If your DataTable has a primary key defined, you can find the row like this:
DataTable table = ds.Tables["SomeTable"];
DataRow row = table.Rows.Find(1);
If there is no primary key, you can assign one like this:
DataTable table = ds.Tables["SomeTable"];
table.PrimaryKey = new DataColumn[] { table.Columns["SomeID"] };
DataRow row = table.Rows.Find(1);
Another option is to use the RowFilter property of the DefaultView, like this:
DataTable table = ds.Tables["SomeTable"];
table.DefaultView.RowFilter = "SomeID == 1"; //not sure if it's == or = here
DataRow row = table.DefaultView[0].Row;
Lastly, you can also use the DataTable.Select() method to find rows.
Have you looked at using a typed dataset? If you're looking for a row based on the primary key of a table it will autogenerate a method for you to get a row by ID and it will be strongly typed so you can get column values by name.
They were quite handy in .Net 2.0 - but LINQ made them fairly obsolete.
Edit: A slightly better reference URL
http://www.c-sharpcorner.com/UploadFile/rupadhyaya/TypedDataSets12032005021013AM/TypedDataSets.aspx
We can get value from dataset by using this easy method:
System.Data.DataSet ds = db.MySelect(
"Fields",
"Table",
"Condition"
);
if (ds != null)
{
if (ds.Tables[0].Rows.Count > 0)
{
object value=Tables[0].Rows[indx]["field name"];
}
}
To fetch values from student table and display it in console window.
class Class1
{
static void Main(string[] args)
{
SqlConnection con=new SqlConnection(<connectionstring>);
SqlCommand cmd = new SqlCommand("select * from Student", con);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataSet ds=new DataSet();
ad.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
try
{
DataRow r = ds.Tables[0].Rows[i];
Console.WriteLine(r.Field<Int32>(0));
Console.WriteLine(r.Field<String>(1));
Console.WriteLine(r.Field<String>(2));
Console.WriteLine(r.Field<Decimal>(3));
Console.WriteLine(r.Field<Int16>(4));
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
Console.ReadKey();
}
}
sql Student table Info
Id int
Name varchar(50)
EmailId nvarchar(50)
MobileNo numeric(10,0)
Standard smallint
Related
I'm trying to retrieve the second row from a DataTable but this is not returning a value. What could be the problem as the DropDown populates just fine.
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
DropDown.DataSource = dt;
DropDown.DataTextField = "FirstName";
DropDown.DataValueField = "FirstName";
DropDown.DataBind();
con.Close();
var secondRow = dt.Rows[2].ToString(); // This should return the second row in my datatable.
}
DataTable.Rows[int] will give you the DataRow object. If you do dt.Rows[2].ToString(), you are going to get the string representation of the object type.
The index starts at 0. Hence for 2nd row, you will query dt.Rows[1]. Further, You can extract the value of a column in the row and for that, you have to mention the column index or name like - dt.Rows[1][0] or dt.Rows[1]["col1"]
You can also loop through all the columns in the row like below:
foreach (DataColumn col in dt.Columns)
{
var columnValue = dt.Rows[1][col];
}
From this code I am trying to only display data rows that contain the fields "DBY" in the Station_From_Code column and "MAT" in the Station_To_Column. This will then be printed onto a HTML page. These fields are definitely in the datatable but when I run this cod the table is empty. I am not used to working with data tables in C# so apologies for the poor coding.
dynamic schedluedContent = JsonConvert.DeserializeObject(scheduledJson);
JArray items2 = new JArray();
foreach (JObject stops in schedluedContent.stops)
{
DataTable dt = new DataTable();
DataRow dr;
dr = dt.NewRow();
dr["From_Station_Code"] = stops["station_code"];
dr["To_Station_Code"] = stops["station_code"];
dt.Rows.Add(dr);
DataRow[] result = dt.Select("From_Station_Code = 'DBY' AND To_Station_Code = 'MAT'");
dt.Rows.Add(result);
GridViewTrainTimes.DataSource = dt;
GridViewTrainTimes.DataBind();
}
It's a long time I have not seen this style of code for working with database tables! EntityFramework comes to change and surely ease the way of working with database and prevent different risks of using SQL commands inside the code.
If you use EF, your code will become something like bellow:
var rows = myDBContext.MyTable.Where(x=>x.From_Station_Code == "DBY" && x.To_Station_Code == "MAT");
GridViewTrainTimes.DataSource = rows;
You can use find match rows and add in new datatable, that contains only your match rows data then you can bind this dt to gridview.
DataTable dt = new Datatable(); // Lets this datatable have data;
Datatable dt2 = new Datatable(); // Copy all matching rows
foreach (DataRow dr in dt.Rows)
{
if (dr["From_Station_Code"].ToString() == "DBY" && dr["To_Station_Code"].ToString() == "MAT")
{
dt2.Rows.Add(dr);
}
}
GridViewTrainTimes.DataSource = dt;
GridViewTrainTimes.DataBind();
How can I filter data from dataset to datatable?
like the code->
DataRow[] dr = DS.Tables[0]
.Select("STAGENAME='Develop' AND DEVLAPSEDAYS IS NOT NULL");
How can I use datatable here?
following code doesn`t reflect changes->
DataTable FilteredDataD = DS.Tables[0];
if (FilteredDataD.Rows.Count > 0) {
FilteredDataD.DefaultView.RowFilter = "STAGENAME='Develop' AND DEVLAPSEDAYS IS NOT NULL";
FilteredDataD.DefaultView.ToTable();
}
Is is possible to remove a column using above filter,like "STAGENAME='Develop' AND DEVLAPSEDAYS IS NOT NULL" + FilteredDataD.column("col_name")...
Suppose I have 5 columns display only 4,I can`t remove col_name from my query.Is there a way?
Reply
Try using LINQ instead:
var table = DS.Tables[0].AsEnumerable().Where(
r => r.Field<string>("STAGENAME") == "Develop" && r.Field<int?>("DEVLAPSEDAYS").HasValue).AsDataView().ToTable();
EDIT Changed AsDataView to AsDataView() for syntactical accuracy.
EDIT Provided .NET 2.0 compatible solution
DataTable table = DS.Tables[0];
if (table.Rows.Count > 0)
{
table.DefaultView.RowFilter = "STAGENAME = 'DEVELOP' AND DEVLAPSEDAYS IS NOT NULL";
table = table.DefaultView.ToTable();
}
You could write an extension method (using C# 3) like follows:
public static DataTable Filter(this DataTable dataTable, string selectFilter)
{
var filteredTable = dataTable.Clone();
var rows = dataTable.Select(selectFilter).ToList();
rows.ForEach(filteredTable.ImportRow);
return filteredTable;
}
Then use it like follows:
DataTable dataTable = DS.Tables[0]
.Filter("STAGENAME='Develop' AND DEVLAPSEDAYS IS NOT NULL");
Update, since you said you are using C# 2.0 (and thus extension methods and LINQ aren't an option) you could use this instead:
public static DataTable GetFilteredTable(
DataTable sourceTable, string selectFilter)
{
var filteredTable = sourceTable.Clone();
var rows = sourceTable.Select(selectFilter);
foreach (DataRow row in rows)
{
filteredTable.ImportRow(row);
}
return filteredTable;
}
DataTable dataTable = GetFilteredTable(
DS.Tables[0], "STAGENAME='Develop' AND DEVLAPSEDAYS IS NOT NULL");
Situation:
Hello! I am trying to populate a WPF toolkit DataGrid with a MS Access database.
Here is what I have right now (it works):
//Load the datagrid with the database
private void LoadDataGrid(string filename, string path)
{
string databaseConn = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + path + "\\" + filename,
tableName ="";
OleDbConnection conn = null;
DataTable schemaTable,
table = new DataTable();
try
{
conn = new OleDbConnection(databaseConn);
try
{
conn.Open();
schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
new object[] { null, null, null, "TABLE" });
tableName = "[" + schemaTable.Rows[0].ItemArray[2].ToString() + "];";
string sqlQuery = "SELECT * FROM " + tableName;
OleDbCommand command = new OleDbCommand(sqlQuery, conn);
OleDbDataReader reader;
reader = command.ExecuteReader();
table.Load(reader);
DataGrid_.ItemsSource = table.DefaultView;
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
}
The code sample above loads a WPF toolkit DataGrid with the help of a MS Access database.
What I would like to do is be able to insert a column in the DataGrid at the very beginning. This column would be used to write the row number. What I think could work is to modify the table variable (which is a DataTable object).
Question:
So, how can I insert a column in the table variable, add the row number for each rows in that new column, and have all the data from the database in the DataGrid?
An alternative is to create a column on the DataTable before loading the IDataReader into it.
// the rest of your code
//
DataTable table = new DataTable();
DataColumn col = table.Columns.Add("RowNumber", typeof(int));
col.AutoIncrementSeed = 1;
col.AutoIncrement = true;
//
// the rest of your code
//
table.Load(reader)
//
// the rest of your code
The code snippet bellow demonstrates the technique out of the question's context
//Simulates data coming from a database or another data source
DataTable origin = new DataTable();
DataColumnCollection columns = origin.Columns;
columns.Add("Id", typeof(int));
columns.Add("Name", typeof(string));
origin.Rows.Add(55, "Foo");
origin.Rows.Add(14, "Bar");
IDataReader reader = origin.CreateDataReader();
DataTable table = new DataTable();
//Sets up your target table to include a new column for displaying row numbers
//These are the three lines that make it all happen.
DataColumn col = table.Columns.Add("RowNumber", typeof(int));
col.AutoIncrementSeed = 1;
col.AutoIncrement = true;
//Simulates loading data from the database
table.Load(reader);
// Examine table through the debugger. Is will have the contents of "origin" with the column "RowNumber" prepended
Your easiest solution would be to modify your code to include a "virtual" RowNumber field in your original SELECT query, like so:
SELECT ROWNUM AS ROWNUMBER, * FROM TABLE1
Unfortunately, Access doesn't have anything like a ROWNUM function, so I think the easiest solution is to add a RowNumber column in the SELECT query like this:
SELECT 0 AS ROWNUMBER, * FROM TABLE1
which will add a column containing all zeroes at the beginning, and then iterate through the resulting DataTable and set the row number, like this:
int rownumber = 1;
foreach (DataRow row in table.Rows)
{
row["ROWNUMBER"] = rownumber;
rownumber++;
}
and then dump the DataTable into the grid.
How do I compare values of one data set from another.
1st dataset ["proper records"] is coming from SQL Server with column names
[id], [subsNumber]
2nd dataset ["proper and inproper records"] is coming from progress database, with different columns except 1 which is subsNumber
How do I go and make another dataset which has all the [subsNumber] from ["proper records"] with matching records from 2nd datset ["proper inproper records"] ?
or
delete all the records in 2nd dataset["proper and inproper records"] which don't match the "subsNumber" column in the 1st dataset
or any other idea
basically How do I get all records from 2nd dataset which has same "subsNumber" as the 1st dataset
The key is using System.Data.DataRelation to join your 2 datatables on a common column (or columns).
Here's some code derived from a post at KC's See Sharp Blog
public DataTable GetImproperRecords(DataTable ProperRecords, DataTable ImproperRecords) {
DataTable relatedTable = new DataTable("Difference");
try {
using (DataSet dataSet = new DataSet()) {
dataSet.Tables.AddRange(new DataTable[] { ProperRecords.Copy(), ImproperRecords.Copy() });
DataColumn properColumn = new DataColumn();
properColumn = dataSet.Tables[0].Columns[1]; // Assuming subsNumber is at index 1
DataColumn improperColumn = new DataColumn();
improperColumn = dataSet.Tables[1].Columns[0]; // Assuming subsNumber is at index 0
//Create DataRelation
DataRelation relation = new DataRelation(string.Empty, properColumn, improperColumn, false);
dataSet.Relations.Add(relation);
//Create columns for return relatedTable
for (int i = 0; i < ImproperRecords.Columns.Count; i++) {
relatedTable.Columns.Add(ImproperRecords.Columns[i].ColumnName, ImproperRecords.Columns[i].DataType);
}
relatedTable.BeginLoadData();
foreach (DataRow parentrow in dataSet.Tables[1].Rows) {
DataRow[] childrows = parentrow.GetChildRows(relation);
if (childrows != null && childrows.Length > 0)
relatedTable.LoadDataRow(parentrow.ItemArray, true);
}
relatedTable.EndLoadData();
}
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
return relatedTable;
}
I solved the problem:
1st dataset--> loop throuhg and get the subsNumber
Call function and pass subsNumber and 2nd dataset--> to it
Then start another loop for new dataset
Continue if subsnumber don't match
If subsNumber match work on that data like add columns to sqlserver table etc.
code:
foreach (DataRow row in ecommDS.Tables["EcommData"].Rows)
{
//string statCode = ""
string prdCode = ""; //declaring var for getting string format from ecomm
string checking = "";
prdCode = row["PRD-CDE"].ToString();
checking = row["SUBS-NUM"].ToString();
if(checking != subsNum)
{
continue;
}
To get all the records from 2nd dataset that match the records from the 1st dataset would be something like this:
IEnumerable list3 = list2.Where(l2=>list1.Contains(l1=>l1.subsNumber == l2.subsNumber));
Something along those lines!