Getting columns from DataTable stored in session - c#

So I have a DataTable which uses:
SELECT * FROM People WHERE ID = ?
You can understand that this will only retrieve one row as the ID is unique:
usersTableAdapters.UsersTableAdapter user = new usersTableAdapters.UsersTableAdapter();
users.UsersDataTable userDataTable = user.getUserInfo(id);
I have then stored the DataTable into a session:
HttpContext.Current.Session.Add("userDT", userDataTable);
Now I am trying to figure out, how would I get a specific column from the userDT in the session? To be more clear the firstname column?

First cast the session object as a datatable.
var tbl = ((DataTable)HttpContext.Current.Session["userDT"])
Then use it like a data table:
var col = tbl.Columns["firstName"];

You have to cast Session object to users.UsersDataTable:
users.UsersDataTable userDataTable = Session["userDT"] as users.UsersDataTable;

Try this,
DataView dv = new DataView((DataTable)HttpContext.Current.Session["userDT"]);
get the table just with column
DataTable dt = dv.ToTable(true, "firstName");

Related

How to sort DataSet by column [duplicate]

This question already has answers here:
Sorting a Data Table
(5 answers)
Closed 4 years ago.
My SQL database was created in SQL Server Management Studio. I have a dataset table that works great, which was sorted by the primary key id column from an example I copied, which was fine when there were only a few entries. Now I want to sort by the Model_no column.
I have tried to sort the table like this:
ds.Tables[0].DefaultView.Sort = "Model_no";
and like this:
DataTable table = ds.Tables[0];
DataView view = table.DefaultView;
view.Sort = "Model_no";
But the table is still sorted by primaryKey.
objConnect = new DatabaseConnection();
conString = "Server=VENUS;" +
"Initial Catalog=TestRig;" +
"User id=TestRig;" +
"Password=act1ve;" +
"MultipleActiveResultSets = true;";
objConnect.connection_string = conString;
objConnect.Sql = Properties.Settings.Default.SQL;
ds = objConnect.GetConnection;
DataTable table = ds.Tables[0]; // Neither this
DataView view = table.DefaultView;
view.Sort = "Model_no";
// ds.Tables[0].DefaultView.Sort = "Model_no"; // or this work
// When I click next record, I inc the row, then get the datarow and
display in my form
inc++;
dRow = ds.Tables[0].Rows[inc];
dummy = dRow.ItemArray.GetValue(0).ToString(); // Primary Id
exVol = dRow.ItemArray.GetValue(1).ToString();
tbExcitationVoltage.Text = exVol.Trim();
When I open the form I expect the first entry to be sorted by the model number, but instead see record 1 (primary ID), how can I sort by another column please?
You need to read from DefaultView. If you need to read from the table you can do the following.
ds.Tables[0].DefaultView.Sort = "Model_no";
DataTable dt = ds.Tables[0].DefaultView.ToTable();

Cannot implicitly convert type 'int' to 'System.Data.DataTable'

I am trying to update some field in my data table. While using the given below code shows one error. Help me to find a proper solution. Thank you.
Code:
ShadingAnalysisDataSetTableAdapters.tbl_AutoAssignJrEngineersTeamTableAdapter tm;
tm = new ShadingAnalysisDataSetTableAdapters.tbl_AutoAssignJrEngineersTeamTableAdapter();
DataTable dt = new DataTable();
dt = tm.UpdateTeam(AssignedTeam,userName,DateTime.Now,ID); // error popup here
SQL:
UPDATE tbl_AutoAssignJrEngineersTeam
SET Assigned_Team = #Assigned_Team,
Updated_By = #Updated_By,
Updated_Date = #Updated_Date
WHERE (Id = #Id)
DataBase:
The TableAdapter-method returns an int which is the count of affected records, so how many records were updated. But you are assigning it to a DataTable variable.
int updatedRows = tm.UpdateTeam(AssignedTeam,userName,DateTime.Now,ID);
You either have to
load the table again with the appropriate GetData- or Fill(dt) methods from the TableAdapter
or update the rows in the table and use tm.Update(modifiedDataTable) instead which will execute the UpdateCommand of the adapater for every row with RowState=Modified.

how to filter the data set contains the values?

I am working on asp.net application and am new to it. Here I have some id like selected=1,2,3 I just want to know that if this id's dataset contains or not? I don't have any idea how to check this.
Here my code
selected=1,2,3
GVSubSelectDtls.DataSource = ds.Tables[0];
DataRow[] foundRows = ds.Tables[0].Select(selected.ToString());
GVSubSelectDtls.DataBind();
but I am getting an error. How can I resolve this?
You need to use Column Names inside Select like:
DataRow[] foundRows = ds.Tables[0].Select("MyColumnName = 'My Column value'");
In your case:
GVSubSelectDtls.DataSource = ds.Tables[0];
DataRow[] foundRows = ds.Tables[0].Select("ID IN ('1','2','3')");
GVSubSelectDtls.DataBind();

Any data table query builder available, like sql query builder?

I am new in net I want to use data table instead of a database.
I want to know that why is data table query different from an sql query?
I want to find a value from data table:
SELECT dbo.General_Ledger.Entry_Amount FROM dbo.General_Ledger WHERE Account_number=lbDebit_Account_numer
and
using (SqlConnection connect = new SqlConnection(con))
{
int index = lbDebit_Account.FindString(txtDebit_Account.Text);
if (0 <= index)
{
lbDebit_Account.SelectedIndex = index;
}
SqlDataAdapter da3 = new SqlDataAdapter("SELECT *FROM dbo.General_Ledger", connect);
DataTable dt1 = new DataTable();
da3.Fill(dt1);
string lbDebit_Account_numer = lbDebit_Account.SelectedValue.ToString();
string row;
row= Convert.ToString(dt1.Select(string.Format("'Account_number'={0}",lbDebit_Account_numer)));
}
I want to perform this query:
SELECT dbo.General_Ledger.Entry_Amount FROM dbo.General_Ledger WHERE Account_number=lbDebit_Account_numer
So you'll want to parameterize your query:
SqlDataAdapter da3 = new SqlDataAdapter("SELECT * FROM dbo.General_Ledger WHERE Account_number = #Account_number");
da3.SelectCommand.Parameters.AddWithValue("#Account_number", lbDebit_Account.SelectedValue);
DataTable dt1 = new DataTable();
da3.Fill(dt1);
and now you'll have just the one row you want and you can recover it like this:
DataRow dr = dt1.Rows[0];
and then you can grab values off of that row a number of different ways:
var val = dr[0]; // grabs the value of the first column in the result list
var val = dr["fieldname"] // grabs the value of a specific field name
and there are even some methods that will returned typed data because the aforementioned return an object since the underlying value could be a number of things. So, if it were a string field you were after you could do something like:
var val = dr.Field<string>(0) // grabs the value of the first column and returns it typed as a string
var val = dr.Field<string>("fieldname") // grabs a field and returns it typed as a string
It very simple, u want to filter the DataTable[dt1] base on this string[lbDebit_Account_numer]
DataRow dr = dt1.Select("Account_number = '"+lbDebit_Account_numer ="'");
u can use
AND OR
operators
single code['] need for string variables to compare.
here u get data-row, all cell will in an array format you select any cell.
You can try to use DefaultView.RowFilter property of DataTable class.
Example:
dataTable.DefaultView.RowFilter = "Account_number=1";

Selected columns from DataTable

How to get the Selected columns form the DataTable? For e.g my BaseTable has three columns, ColumnA, ColumnB and ColumnC. Now as part of intermediate operations, I need to retrieve all the rows only from the ColumnA. Is there any predefined formula just like DataTable.Select?
DataView.ToTable Method.
DataView view = new DataView(MyDataTable);
DataTable distinctValues = view.ToTable(true, "ColumnA");
Now you can select.
DataRow[] myRows = distinctValues.Select();
From this question: How to select distinct rows in a datatable and store into an array you can get the distinct values:
DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "ColumnA");
If you're dealing with a large DataTable and care about the performance, I would suggest something like the following in .NET 2.0. I'm assuming the type of the data you're displaying is a string so please change as necessary.
Dictionary<string,string> colA = new Dictionary<string,string>();
foreach (DataRow row in table.Rows) {
colA[(string)row["ColumnA"]] = "";
}
return colA.Keys;

Categories

Resources