Data table result in grid:
SerialNumber PartNumber
000000001 QWERTY
000000002 QERTY
I need to search a particular SerialNumber in the result of my data table using a Textbox control.
Pseudocode example:
If
SearctTexbox.Text =000000001
Message: This Serial is Ok!
Else
Message: Not Ok
How to do this in LINQ or any other methods?
If SerialNumber column have unique values, so give it a try:
//dt is DataTable
dt.PrimaryKey = new DataColumn[1] { dt.Columns[0] }; // set your primary key
DataRow dRow = dt.Rows.Find(SearchTextbox.Text);
if (dRow != null){
// you've found it
}
else{
//sorry dude
}
Why do you need LINQ? You can try with
dataTable.Select("condition");
try this
var item = from r in Datatable.AsEnumerable()
where r.Field<int>("SerialNumber") == int.Parse(SearchTextbox.Text.ToString())
select r.Field<int>("SerialNumber");
if (item == null)
{
// not found
}
else
{
// you found it.
}
string massage = dc.Parts.Select(
o => o.SerialNumber == SearctTexbox.Text).Count()>0 ? "Found it"!"No Find";
Related
I want to query a specific value from a DataTable.
Lets say i have a DataTable which contains 2 columns:
id
item_name
Now what I want to do is like i would do it with mysql: SELECT * FROM "DataTable" WHERE item_name = 'MyItemName'
And then get the id that belongs to that 'item_name'...
int blah;
while (MyReader.Read())
{
blah = MyReader.GetInt32("id");
}
Now: how can I do this using DataTable?
I've got a snippet but I can't seem to show the returned value in a messagebox:
string test = Item1txt.Text;
var query = producten.Rows.Cast<DataRow>().Where(x => x.Field<string>("item_name") == test);
foreach (var st in query)
{
MessageBox.Show(st.ToString());
// how can i show the id that belongs to "test" ?
}
query will be an IQueryable<DataRow>, so st will be a DataRow. Try this:
foreach (var st in query)
{
MessageBox.Show(st.Field<int>("id").ToString());
}
Or if you know there will only item with that item_name, here's an alternative version which does essentially the same thing, but is probably a bit easier to understand:
var st = producten.Rows.Cast<DataRow>().FirstOrDefault(x => x.Field<string>("item_name") == test);
if(item != null)
{
MessageBox.Show(st.Field<int>("id").ToString());
}
You can use linq directly on the datatable without the need of Rows or the Cast.
var query = producten.AsEnumerable().Where(x => x.Field<string>("item_name") == test);
foreach (var st in query)
{
MessageBox.Show(st.Field<int>("id"));
}
I usually use the Rowfilter property of the defaultview of the datatable, but I must admit I never did LINQ myself, so there's probably a better way now...
I am trying to find a fast way to find a string in a Column in a DataTable and add it to a comboBox, and this is the code i tried so far :
adapter = new SqlDataAdapter("Select Id_Editeur ID,Libelle_Editeur Editeur from Editeur", myClass.cnx);
adapter.Fill(myClass.ds, "Editeur");
foreach (String str in myClass.ds.Tables["Editeur"].Columns[1].ToString())
editeurBox.Properties.Items.Add(str);
and that's doesn't work it gives me this error :
foreach statement cannot operate on variables of type
'System.Data.DataColumn' because 'System.Data.DataColumn' does not
contain a public definition for 'GetEnumerator'
How can I do that ? (I don't want the for loop solution).
foreach (var row in myClass.ds.Tables["Editeur"].AsEnumerable())
{
editeurBox.Properties.Items.Add(row[1].ToString());
}
or Full linq-style:
editeurBox.Properties.Items.AddRange(
myClass.ds.Tables["Editeur"]
.AsEnumerable()
.Select(dr => dr[1].ToString()
);
You can try with this code - based on LINQ Field operator
var results = from myRow in myDataTable.AsEnumerable()
where myRow.Field<string>("RowNo") == "yourSearch"
select myRow;
I think you need to loop through the rows and grab the column that you want. Your code is trying to loop through the column collection which doesn't contain any data:
foreach (DataRow row in myClass.ds.Tables["Editeur"].Rows)
editeurBox.Properties.Items.Add(row[1].ToString());
string TableSelect;
DataTable dt = GetSomeData();
foreach (DataRow row in dt.Rows)
{
TableSelect = "EmplNo = " + row["EmplNo"].ToString();
DataRow[] foundrows;
foundrows = dt.Select(TableSelect);
if (foundrows.Count() > 0)
{
//do something useful here :)
}
}
Using linq2sql I'm trying to take the string in txtOilChange and update the oilChange integer in the car table of the white fusion.
I know my code below is wrong but what do I need to change?
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
var o = (from c in db.cars
where c.carDesc == "White Fusion"
select c).First();
txtOilChange.Text = o.oilChange.ToString();
db.SubmitChanges();
}
If you're trying to update the record it looks like the assignment statement is reversed.
This:
txtOilChange.Text = o.oilChange.ToString();
Should be:
o.oilChange = int.Parse(txtOilChange.Text);
For better error handling consider using the TryParse method:
int oilChangeValue;
if (int.TryParse(txtOilChange.Text, out oilChangeValue))
{
o.oilChange = oilChangeValue;
db.SubmitChanges();
}
else
{
// invalid value
}
I have this Code for Reading Excell Records:
public IEnumerable<FillinEntity> Map(IEnumerable<ExcelRow> excelRows)
{
List<FillinEntity> fillinEntities = new List<FillinEntity>();
foreach (ExcelRow row in excelRows)
{
FillinEntity excell = new FillinEntity();
excell.SerialNumber = Convert.ToString(row.Cells[0]);
excell.PalletNumber = Convert.ToString(row.Cells[1]);
excell.Location = Convert.ToString(row.Cells[2]);
excell.CreatedBy = Convert.ToString(row.Cells[3]);
fillinEntities.Add(excell);
}
return fillinEntities;
}
I have this records: And it succesfully inserted
R03091294 2 2 FGROOM RYAN
My Problem: I Add column header on the excell sheet.
Serial Number Pallet Location CreatedBy -----> i need to by pass column header.
R03091294 2 2 FGROOM RYAN
Thanks in regards
You could always just skip it:
foreach (ExcelRow row in excelRows.Cast<ExcelRow>().Skip(1))
See Skip().
Note: I used Cast<ExcelRow>() in case your enumerable excelRows can't be resolved to ExcelRow.
bool is_first_row = True;
foreach (ExcelRow row in excelRows)
{
if(is_first_row)
{
is_first_row = false;
continue;
}
...
}
....
.Skip(1)
solution provided by Codesleuth is much better option.
I have a small winapp that uses LinqToSQL as it's DAL. I am creating a summary view of all the CaseNotes for a given person and one of the fields is a Details box. I need to return only the first 50 characters of that column to my treeview function.
Any hints on how I do that? The below is how my TreeView function gets its data for display and the ContactDetails is the column in question.
public static DataTable GetTreeViewCNotes(int personID)
{
var context = new MATRIXDataContext();
var caseNotesTree = from cn in context.tblCaseNotes
where cn.PersonID == personID
orderby cn.ContactDate
select new { cn.CaseNoteID,cn.ContactDate, cn.ParentNote, cn.IsCaseLog, cn.ContactDetails };
var dataTable = caseNotesTree.CopyLinqToDataTable();
context.Dispose();
return dataTable;
}
ANSWER
I am posting this here in case any future searchers wonder what the solution looks like in the questions context.
public static DataTable GetTreeViewCNotes(int personID)
{
DataTable dataTable;
using (var context = new MATRIXDataContext())
{
var caseNotesTree = from cn in context.tblCaseNotes
where cn.PersonID == personID
orderby cn.ContactDate
select new
{
cn.CaseNoteID,
cn.ContactDate,
cn.ParentNote,
cn.IsCaseLog,
ContactDetailsPreview = cn.ContactDetails.Substring(0,50)
};
dataTable = caseNotesTree.CopyLinqToDataTable();
}
return dataTable;
}
String.Substring:
var caseNotesTree = from cn in context.tblCaseNotes
where cn.PersonID == personID
orderby cn.ContactDate
select new {
cn.CaseNoteID,
cn.ContactDate,
cn.ParentNote,
cn.IsCaseLog,
ContactDetailsClip = cn.ContactDetails.Substring(0, Math.Min(cn.ContactDetails.Length, 50))
};
Also, I would suggest wrapping your use of DataContexts in using blocks.
With LinQ you can also do the following :
new string( myString.Take(50).ToArray() );
cn.ContactDetails.Substring(0, 50);
In the "select new" line. Does that work?
LINQ syntax
string message=new string(myString.Take(50).ToArray());