Searching DataTable with string containing space c# - c#

So I've done a lot of searching for this one and can't figure it out. I have a csv file that i'm writing off to a DataTable and populating a combo box from that same datatable. The Idea is to search a user selected value in the data table and return the ID of that selection from the same data table. The problem I'm having is that the selections all have spaces since they are capacity environments. Is there a way to take the string and search the datatable column "Description" and return the column "ID"? here is the code:
internal static void envRequest(string e)
{
DataRow[] foundRows;
foundRows = variables.capEnvTable.Select(e);
//variables.envID = foundRows[0].ToString();
Thread.Sleep(200);
Console.WriteLine(foundRows.ToString());
}
}
The DataTable is formated as "ID" - "Name" - "Description"
The value of e is the user selected value such as "Buckeye Hosting Zone 2 Aries"
Right now I'm getting a System.Data.SyntaxErrorException: 'Syntax error: Missing operand after 'Hosting' operator.' on the
foundRows = variables.capEnvTable.Select(e);

Ok lets say the first column (index 0) is the value you want to search and the 2nd column (index 1) is the value you want.
DataRow dataRow;
dataRow =
myDataGridView.Rows.Cast<DataRow>()
.FirstOrDefault( row => row[0] == "ValueYouWantToSearch" );
var value = dataRow[1];

Related

How to select from a datatable where the column is part of a string in C#.net

I have a datatable that I am trying to make an update on.
my datatable is the data source of a data gridview (Forms application)
I want to update all rows that are part of a textbox
the textbox contains a comma separated values such as
A1,A11,B4,B38,C44
I have this code but stuck on how to make it working
DataTable dt = new DataTable();
dt = (DataTable)grd1.DataSource;
DataRow[] dr = dt.Select("'," + TextBox1.Text + ",' LIKE '%,Code,%'");
foreach (DataRow row in dr)
{
row["Price"] = 1000;
}
The problem is in this code
"'," + TextBox1.Text + ",' LIKE '%,Code,%'"
it does not retuen any rows so I think I did not write it the right way.
How to fix my select line?
Note : I added a comma before and after so I do not get "T37" when I am looking for "T3"
Your question wasn't easy to understand for me, but you seem to be saying that you will type a list of values into the textbox and these values are to be looked up in the [Code] column of the datatable. I'm not clear on whether the Code column itself is a single value or a comma separated list of codes, so I'll answer for both. Assuming the Code column is a CSV, and you want that any row where any one of the values in Code is one of these values in the textbox, shall have its price updated to 1000:
So for a textbox of "A1,B1" and a datarows like:
Code Price
A1,C3 200
B4,C7 400
The 200 row shall be updated and the 490 row shall not
I'd use LINQ for this rather than datatable select
var codes = textbox.Split(',');
var rows = dt.AsEnumerable().Where(r => codes.Any(c => (r["Code"] as string).Split(',').Contains(c)));
foreach(var r in rows)
r["Price") = 1000;
If you're doing this a lot I wouldn't have the codes in the row as a CSV string; a row field is allowed to be an array of strings - storing the codes as an array in the row will save having to split them every time you want to query them
If I've got this wrong and the row contains just a single Code value, the logic is the same, it just doesn't need the split(though the code above would work, it's not optimal):
var rows = dt.AsEnumerable().Where(r => codes.Any(c => (r["Code"] as string) == c));
And actually if you're going to be doing this a lot, I would index the datatable:
//if it's a csv in the datatable
var index = dt.AsEnumerable()
.SelectMany(r => r["Code"].ToString().Split(','), (row, code) => new { R=row, C=code})
.ToLookup(o => o.C, o => o.R);
This will give something like a dictionary where a code maps to a list of rows where the code appears. For a row set like
Code Price
A1,C3 200
B4,C3 400
You get a "dictionary" like:
A1: { "A1,C3", 200 }
C3: { "A1,C3", 200 },{ "B4,C3", 400 }
B4: { "B4,C3", 400 }
so you could:
foreach(var c in codesTextbox.Split)
foreach(var row in index["c"])
row["Price"] = 1000;
If the Code column doesn't contain a csv, doing a selectmany should still be fine, but to optimize it:
var index = dt.AsEnumerable().ToLookup(r => (string)r["Code"]);

how to get a last column value in a Templorary datatable (.net)

I am storing some values in a temporary datatable.Sample values as follows
ID FILENAME PATH
--------------------------
1 txt1 C:\NewFolder
2 txt2 C:\NewFolder
3 txt3 C:\NewFolder
I want to get the last value of ID column.
You can use such code to get the last row and then the value from column ID:
object lastId = table.Rows[table.Rows.Count-1]["ID"];
If by last you meant that you need the maximum value from the table you can use the following LINQ query to get the result:
int maxValue= table.AsEnumerable().Select(row => Convert.ToInt32(row["ID"])).Max();
You need to have the following using in order for it to work:
using System.Data.DataSetExtensions;
string expression = "1=1"
// Sort descending by column named CompanyName.
string sortOrder = "ID DESC";
DataRow[] foundRows;
// Use the Select method to find all rows matching the filter.
foundRows = table.Select(expression, sortOrder);
var row = foundRows[0];
Ref:https://msdn.microsoft.com/en-us/library/way3dy9w(v=vs.110).aspx

Extract data from the last row of gridview in ASP.net

I know how to to do it and put the data on textbox when I select a row from a gridview, What I want to achieve now is when I open a modal pop up form containing a gridview, it will automatically select or extract the date column from the last row of gridview.
This is for the purpose of determining the last date from the record.
Here's what I got so far (under click event for button "ADD")
if (grdSpecificTenantRental.Rows.Count == 0)
{
txtdatefrom.Text = "No record yet";
}
else
{
GridViewRow rowtwo = grdSpecificTenantRental.Rows[grdSpecificTenantRental.Rows.Count - 1];
string index = rowtwo.Cells.ToString();
txtdatefrom.Text = index;
}
Here's the output int he textbox: System.Web.UI.WebControls.TableCellCollection
Obviously this line is incorrect: string index = rowtwo.Cells.ToString();
I want to extract the 4th column in the last row which is the end date
Currently you are getting all the cells that is CellCollection so if you want to get perticular column value then use that array's index to get the required columns value.As you mentioned 4th columns so use the index 3 because index starts from 0.You might want to access it like this,
txtDateFrom.Text = grdSpecificTenantRental.Rows[grdSpecificTenantRental.Rows.Count - 1].Cells[3].Text;

Elegant approach to get a CSV string from selected data rows in a datagrid

I have a datatable containing system profile names. This table is then assigned as the data source of a data grid where the administrator will mark multiple rows as selected.
I'd like to store the selected profile names as a comma separated string.
I was going to do it like this:
string AllowedProfiles = string.Empty;
// Retrieve the selected profiles from the data grid
DataRow[] profiles = (this.dgv_SecurityProfiles.DataSource as System.Data.DataTable).Select("profile_OK = 1");
// Ensure we have some data to assign to the CSV string
if( profiles != null && profiles.Length > 0 )
{
// Build the CSV string of the selected names.
foreach( DataRow row in profiles )
{
// Use the second column in the DataTable (first is the check column)
AllowedProfiles += string.Format("{0},", row[1]);
}
// Remove the last comma
AllowedProfiles = AllowedProfiles.Substring(0, AllowedProfiles.Length - 1);
}
Whilst the above code works I don't feel it's the most elegant way forward.
Any suggestion on how I could improve it?
You can use this linq query
string AllowedProfiles = profiles.Aggregate(string.Empty, (current, row) => current + string.Format(",{0}", row[1])).Remove(0,1);

ASP.NET DATA TABLE Traverse Problem

I am getting the Data table a output from my DataAccess Layer.
In My Datatable I am getting users Name,Number,Qualification
I want to assign a users name,number,qualification to a textbox for a particular user id,
How can i do that.
Help
Suppose you got datatable dt from the DAL
Then
var row = from t in dt
where t["userId"]='userid'
select t;
since you got row related to a user now you can use it to assign to the textboxs
txtName.Text = row["Name"]
assuming the datatable has 1 row:
DataRow row = table.Rows[0];
textbox1.text = row["Name"];
textbox2.text = row["Number"];
and so on
if there are multiple rows in the datatable, you need to select the row with that particular used id
DataRow row = table.Select("ID=" + UserID.ToString());
You have to pay attention to NULL values and number of rows.
if (table.Rows.Count == 1)
{
DataRow row = table.Rows[0];
NameTextBox.Text = row.IsNull("name") ? string.Empty : row["name"];
NumberTextBox.Text = row.IsNull("number") ? string.Empty : row["number"];
}
else
{
// Deal with no rows from DL
}
Using ternary operator makes you sure, you delete content of TextBoxes in case you reload row within already filled up page.
Also you may consider to used typed dataset, and access to columns will be generated by xsd.exe.

Categories