I have three select statements,
select 1 from tbl1;
select 2 from tbl2;
select 3 from tbl3;
and in my front end i use a Datatable to retrieve the value from sql.
datatable dt = new datatable(); dt = obj.funcgetval();
gridview.DataSource = dt; gridview.Databind();
I want to select a particular data from the datatable like in a dataset we use ds.tables[0], how can we apply the same in a datatable?
You can use combination of Rows and Columns to read / write particular cell of datatable.
dataTable.Rows[rowsIndex].Column["ColumnName"] = "SomeValue";
string strValue = dataTable.Rows[rowsIndex].Column["ColumnName"].ToString();
To iterate through dataTable
foreach(DataRow row in dt.Rows)
{
string name = row["name"].ToString();
string description = row["description"].ToString();
}
If you want to select any row then use
DataRow dr=dt.Rows[Rowindex];
If you want to get any column value then
object obj=dt.Rows[Rowindex][columnindex];
or
object obj=dt.Rows[Rowindex]["ColumnName"];
This should work for you:
dt.Rows[rowindex]["ColumnName"].ToString();
If you want select specific cell value from Datatable,you can use..
dt.Rows[row index]["Column name"].TOString();
like if you want to select 1st row value from column say Name then use
dt.Rows[1]["Name"].TOString();
if u want select particular row itself you can use Select with filtercondition.
string FilterCond = ur condition;
DataRow[] myrow = dt.Select(FilterCond);
Related
I have list of all days in a month (as GridView header) refer to which month is selected by user which then be displayed in GridView.
Display list of Days in a month
Dim dt As New DataTable
Dim col As New DataColumn
dt.Columns.AddRange(New DataColumn(0) {New DataColumn("Date")})
For i As Integer = 1 To gsTotalDD 'gsTotalDD is total of days in a month
dt.Columns.Add(i)
Next
dt.Rows.Add("Status")
gvRptStatus.DataSource = dt
gvRptStatus.DataBind()
I had a table named tblUpload inside the database which storing data that been uploaded together with date of data uploaded.
What I am trying to do is looping through all the header value (list of days) and check either there is day matching with the date of data uploaded. When there is matching value, the status row on the code dt.Rows.Add("Status") will show status done and leave cell empty if no matching days found.
Example : GridView date (fist row), second header column is 1 and check with database has matching value or not. If yes then on (second row) status, at second column will display done.
EDIT
So I came up with checking the matching value like this :
Dim lCnn As New SqlConnection(gsConnString)
Dim lCmd As New SqlCommand
Dim lsCmd As String
Dim dt As New DataTable
Dim newDt As New DataTable
Dim sda As New SqlDataAdapter
Dim dtrow As DataRow = newDt.NewRow()
lCnn.Open()
lCmd.Connection = lCnn
lsCmd = "SELECT DISTINCT DATEPART (d, [date])"
lsCmd &= " FROM dbUpload..tblUpload"
lCmd.CommandText = lsCmd
sda.SelectCommand = lCmd
sda.Fill(newDt)
dt.Columns.AddRange(New DataColumn(0) {New DataColumn("Date")})
For i As Integer = 1 To gsTotalDD 'gsTotalDD is total of days in a month
dt.Columns.Add(i)
value2 = i
For Each col As DataColumn In newDt.Columns
value = newDt.Rows(i - 1).Item(col)
If value = value2 Then
MsgBox("Same value")
End If
Next
Next
By doing this, I manage to check the value but it's not the right way to do it since I wanted to set the status as done if got matching value or leave status empty if vice versa.
Thank you.
I have a dataset populated from a database:
dataset_original = new DataSet()
data_adapter.Fill(dataset_original)
and I cloned it:
dataset_cloned = dataset_original.Clone()
I cloned it because 1 of the columns in the original is of type int, and I want to change that to type string:
dataset_cloned.Tables(0).Columns("int_column_name_goes_here").DataType = GetType(String)
Now I need to populate the new dataset with the data from the old dataset. How do I do that?
I am using asp.net 1.1 coded with vb.net.
This simple loop should work (even with OPTION STRICT ON):
Dim dataset_cloned = dataset_original.Clone()
dataset_cloned.Tables(0).Columns("int_column_name_goes_here").DataType = GetType(String)
For i As Int32 = 0 To dataset_original.Tables.Count - 1
Dim tbl_original As DataTable = dataset_original.Tables(i)
Dim tbl_cloned As DataTable = dataset_cloned.Tables(i)
For Each row As DataRow In tbl_original.Rows
tbl_cloned.Rows.Add(row.ItemArray)
Next
Next
assuming you have only one table in the data set, you can do something like this.
int ColumnIndex = 0; //Column index of your data you want to copy
for (int i = 0; i < dataset_original.Tables[0].Rows.Count; i++)
{
dataset_cloned.Tables[0].Rows[i].SetField(ColumnIndex, dataset_original.Tables[0].Rows[ColumnIndex].ItemArray[0].ToString());
}
in the same for loop you can copy remaining columns data
if i use = instead of > in line below
TextBox1.Text = "regdate > '12/12/2012 8:27:09'";
it return me zero rows . Any reason ?
DataView dv1 = new DataView ();
DataSet ds = new DataSet ();
DataTable dt = new DataTable();
/*
col1 col2 col3 col4 col5
1 sw#yahoo.com sw Stephen Walther 12/12/2012 8:27:09 PM
2 as#yahoo.com as Al Stevens 12/12/2012 8:27:09 PM
*/
// Here is the code and criteria for selecting few rows based on datetime .
TextBox1.Text = "regdate > '12/12/2012'";
//connection created
SqlConnection con = new SqlConnection(SqlDataSource1.ConnectionString);
con.Open();
SqlDataAdapter da = new SqlDataAdapter ("SELECT * FROM users",con);
da.Fill (ds);
// filtering criteria applied .
DataRow[] dr = ds.Tables["Table"].Select(TextBox1.Text);
//columns created
dt.Columns.Add("col1", typeof(int));
dt.Columns.Add("col2", typeof(string));
dt.Columns.Add("col3", typeof(string));
dt.Columns.Add("col4", typeof(string));
dt.Columns.Add("col5", typeof(DateTime));
// data added
foreach (DataRow item in dr)
{
dt.Rows.Add(item.ItemArray);
}
// view created
dv1 = dt.DefaultView ;
GridView1.DataSourceID = string.Empty;
GridView1.DataSource = dv1 ;
Page.DataBind();
Because it's a datetime field, so it will compare the whole date and time value, not just the date.
The value 12/12/2012 8:27:09 PM and 12/12/2012 are not the same, because the 12/12/2012 gets expanded to the 12/12/2012 12:00:00 AM value to be comparable to the datetime value. The datetime value doesn't get truncated to be comparable to the date value.
Generally when data types doesn't match for a comparison or calculation, the smaller type gets expanded to the larger type, so that there is no unintentional data loss.
Because the time component is stopping the match - it is trying to match the date AND time.
You could try to use some kind of DATEDIFF function to just match the date portion
How to test two datetimes for equality in T-SQL (ignoring their time components)?
BUT - when amending the code just be really careful with this - not to start putting text box input into the SQL statement. Injection attack risk aplenty.
I think you are OK as it stands but....
The database stores the date in (about) millisecond resolution. When "12/12/2012 8:27:09 PM" is displayed, there is probably a millisecond part that is not displayed, but will throw off a comparison with a date that doesn't specify those milliseconds.
The ">" comparison will succeed because the stored date is higher than your specified date, precisely because of those milliseconds.
I Want to find the value from dataset column Id.
here is the dataset
Id Value
1 football
2 Tennis
3 Cricket
If any one is absent in Column then i want to append that particular value in the dataset
I guess that is a DataTable inside a DataSet. First you need to query if the id is in the DataTable:
var dataTable = dataSet.Tables[0]; //For this example I'm just getting the first DataTable of the DataSet, but it could be other.
var id = 1;
var value = "football";
//Any(...) will return true if any record matches the expression. In this case, the expression is if a Id Field of the row is equals to the provided id
var contained = dataTable.AsEnumerable().Any(x =>x.Field<int>("Id") == id);
Then, if it's not there, add a new row:
if(!contained)
{
var row = dataTable.NewRow();
row["Id"] = id;
row["Value"] = value;
dataTable.Rows.Add(row);
}
Hope it helps
First you should use a loop to see if your dataset column 'id' contains the value. If the id is not existing then:
DataRow newrow = ds.Tables[0].NewRow(); //assuming ds is your dataset
newrow["id"] = "your new id value";
newrow["value"] = "your new value";
ds.Tables[0].Rows.Add(newrow);
i got a select query that returns one row.
here is my DAL function:
public Test.RequestsDataTable getRequestById2(int rid)
{
RequestsTableAdapter adapter2 = new RequestsTableAdapter();
Test.RequestsDataTable dt2 = adapter2.GetData(rid);
return (dt2);
}
Test.xsd is tableAdapter.
my question is how do i call it from code behind file and get each cell value and store it in textbox.
It's a method. Call it.
It returns a Test.RequestsDataTable. If your table has columns Column1 and Column2, then you can do:
var dt = getRequestById2(123);
string col1 = dt.Column1;
int col2 = dt.Column2;
If that doesn't answer your question, then you need to be more clear in your question.
i wrote it in cs file:
Test.RequestsDataTable rdt = new DalObj().getRequestById2(111);
rdt.Columns[0] -> returns DataColumn so i defined
DataColumn c1 = rdt.Columns[0];
but i get the column name and not it's value.