Find row in datatable with specific id - c#

I have two columns in a datatable:
ID, Calls.
How do I find what the value of Calls is where ID = 5?
5 could be anynumber, its just for example. Each row has a unique ID.

Make a string criteria to search for, like this:
string searchExpression = "ID = 5"
Then use the .Select() method of the DataTable object, like this:
DataRow[] foundRows = YourDataTable.Select(searchExpression);
Now you can loop through the results, like this:
int numberOfCalls;
bool result;
foreach(DataRow dr in foundRows)
{
// Get value of Calls here
result = Int32.TryParse(dr["Calls"], out numberOfCalls);
// Optionally, you can check the result of the attempted try parse here
// and do something if you wish
if(result)
{
// Try parse to 32-bit integer worked
}
else
{
// Try parse to 32-bit integer failed
}
}

You can use LINQ to DataSet/DataTable
var rows = dt.AsEnumerable()
.Where(r=> r.Field<int>("ID") == 5);
Since each row has a unique ID, you should use Single/SingleOrDefault which would throw exception if you get multiple records back.
DataRow dr = dt.AsEnumerable()
.SingleOrDefault(r=> r.Field<int>("ID") == 5);
(Substitute int for the type of your ID field)

I could use the following code.
Thanks everyone.
int intID = 5;
DataTable Dt = MyFuctions.GetData();
Dt.PrimaryKey = new DataColumn[] { Dt.Columns["ID"] };
DataRow Drw = Dt.Rows.Find(intID);
if (Drw != null) Dt.Rows.Remove(Drw);

You can try with method select
DataRow[] rows = table.Select("ID = 7");

DataRow dataRow = dataTable.AsEnumerable().FirstOrDefault(r => Convert.ToInt32(r["ID"]) == 5);
if (dataRow != null)
{
// code
}
If it is a typed DataSet:
MyDatasetType.MyDataTableRow dataRow = dataSet.MyDataTable.FirstOrDefault(r => r.ID == 5);
if (dataRow != null)
{
// code
}

try this code
DataRow foundRow = FinalDt.Rows.Find(Value);
but set at lease one primary key

Hello just create a simple function that looks as shown below.. That returns all rows where the call parameter entered is valid or true.
public DataTable SearchRecords(string Col1, DataTable RecordDT_, int KeyWORD)
{
TempTable = RecordDT_;
DataView DV = new DataView(TempTable);
DV.RowFilter = string.Format(string.Format("Convert({0},'System.String')",Col1) + " LIKE '{0}'", KeyWORD);
return DV.ToTable();
}
and simply call it as shown below;
DataTable RowsFound=SearchRecords("IdColumn", OriginalTable,5);
where 5 is the ID.
Thanks..

Try avoiding unnecessary loops and go for this if needed.
string SearchByColumn = "ColumnName=" + value;
DataRow[] hasRows = currentDataTable.Select(SearchByColumn);
if (hasRows.Length == 0)
{
//your logic goes here
}
else
{
//your logic goes here
}
If you want to search by specific ID then there should be a primary key in a table.

Related

How to determine a session variable contains data table is null or empty in C#

I have a Session variable Session["tblItems"], The session variable holds a datatable. Please find my code below.
public JsonResult SaveItemToTable(string itemCode, int quantity, int Division)
{
try
{
DataTable dt = new DataTable("tblItems1");
if(!string.IsNullOrEmpty(Session["tblItems"] as string))
{
dt = (DataTable)Session["tblItems"];
DataRow[] i = dt.Select("ItemCode ='" + itemCode + "'");
if (i.Count() > 0)
{
for (int j = dt.Rows.Count - 1; j >= 0; j--)
{
DataRow dr1 = dt.Rows[j];
if (dr1.ItemArray[0].ToString() == itemCode)
{
dr1.Delete();
}
}
}
}
else
{
dt.Columns.Add("ItemCode", typeof(string));
dt.Columns.Add("Quantity", typeof(int));
dt.Columns.Add("Division", typeof(int));
}
DataRow dr;
dr = dt.NewRow();
dr["ItemCode"] = itemCode;
dr["Quantity"] = quantity;
dr["Division"] = Division;
dt.Rows.Add(dr);
Session["tblItems"] = dt;
return Json(1);
}
catch(Exception ex)
{
return Json(0);
}
}
When the Session variable is empty , the code works fine (Only for the first time).
all the times
if(!string.IsNullOrEmpty(Session["tblItems"] as string))
The above code returns false. Even if the session variable contains value.
Your test is returning false because you are using a 'safe cast': as casting will return null if the conversion can't be made (see more on the C# guide here). Since you are trying to cast a datatable to a string, this will always return null, even when your session variable has a value.
To see the true nature of your problem, try converting them like this:
if(!string.IsNullOrEmpty((string)Session["tblItems"]))
This should thrown an exception, because you can't convert a datatable to a string like this. You will need to test for null like this:
if (Session["tblItems"] != null))
Update: having seen your comments, above, I've added a fuller example to explain what need to change. Your code should look more like this:
DataTable dt;
if (Session["tblItems"] != null))
{
dt = (DataTable)Session["tblItems"];
...
}
else
{
dt = new DataTable("tblItems1");
...
}
DataRow dr;
dr = dt.NewRow();
...
Note the changes I've made: initialise dt from session if there is a value, the cast will work in this case, and when it is null, construct a new one. You can then use the value in the section below without issue, because it will always have a value.
In addition, I would also recommend that you don't store your datatable in session at all, but rather just the values that you need.
To check if your Session is null or empty (for DataTable):
private bool IsDataTableNullOrEmpty(object arg) =>
arg == null || ((DatTable)arg).Rows.Count == 0;

Compare received string from UART to each row in a column in C# GUI [duplicate]

I have two columns in a datatable:
ID, Calls.
How do I find what the value of Calls is where ID = 5?
5 could be anynumber, its just for example. Each row has a unique ID.
Make a string criteria to search for, like this:
string searchExpression = "ID = 5"
Then use the .Select() method of the DataTable object, like this:
DataRow[] foundRows = YourDataTable.Select(searchExpression);
Now you can loop through the results, like this:
int numberOfCalls;
bool result;
foreach(DataRow dr in foundRows)
{
// Get value of Calls here
result = Int32.TryParse(dr["Calls"], out numberOfCalls);
// Optionally, you can check the result of the attempted try parse here
// and do something if you wish
if(result)
{
// Try parse to 32-bit integer worked
}
else
{
// Try parse to 32-bit integer failed
}
}
You can use LINQ to DataSet/DataTable
var rows = dt.AsEnumerable()
.Where(r=> r.Field<int>("ID") == 5);
Since each row has a unique ID, you should use Single/SingleOrDefault which would throw exception if you get multiple records back.
DataRow dr = dt.AsEnumerable()
.SingleOrDefault(r=> r.Field<int>("ID") == 5);
(Substitute int for the type of your ID field)
I could use the following code.
Thanks everyone.
int intID = 5;
DataTable Dt = MyFuctions.GetData();
Dt.PrimaryKey = new DataColumn[] { Dt.Columns["ID"] };
DataRow Drw = Dt.Rows.Find(intID);
if (Drw != null) Dt.Rows.Remove(Drw);
You can try with method select
DataRow[] rows = table.Select("ID = 7");
DataRow dataRow = dataTable.AsEnumerable().FirstOrDefault(r => Convert.ToInt32(r["ID"]) == 5);
if (dataRow != null)
{
// code
}
If it is a typed DataSet:
MyDatasetType.MyDataTableRow dataRow = dataSet.MyDataTable.FirstOrDefault(r => r.ID == 5);
if (dataRow != null)
{
// code
}
try this code
DataRow foundRow = FinalDt.Rows.Find(Value);
but set at lease one primary key
Hello just create a simple function that looks as shown below.. That returns all rows where the call parameter entered is valid or true.
public DataTable SearchRecords(string Col1, DataTable RecordDT_, int KeyWORD)
{
TempTable = RecordDT_;
DataView DV = new DataView(TempTable);
DV.RowFilter = string.Format(string.Format("Convert({0},'System.String')",Col1) + " LIKE '{0}'", KeyWORD);
return DV.ToTable();
}
and simply call it as shown below;
DataTable RowsFound=SearchRecords("IdColumn", OriginalTable,5);
where 5 is the ID.
Thanks..
Try avoiding unnecessary loops and go for this if needed.
string SearchByColumn = "ColumnName=" + value;
DataRow[] hasRows = currentDataTable.Select(SearchByColumn);
if (hasRows.Length == 0)
{
//your logic goes here
}
else
{
//your logic goes here
}
If you want to search by specific ID then there should be a primary key in a table.

i want to check the the given value present in a dataset column or not

I want to check the given value present in a dataset column.
I was insert the value using separator and stored in a column name fld empname.
Example the dataset field fldempname have the value Hari,vinoth,Arun. suppose i ll insert again the value hari and arun means it display error message Like this Employee name already present otherwise the value inserted.
please help me..
My partial code is here..
for (int i = 0; i < lstbox.Items.Count; i++)
{
if (lstbox.Items[i].Selected)
{
string id = lstbox.Items[i].Text;
DataSet4TableAdapters.sp_getallattendancesetupTableAdapter TA1 = new DataSet4TableAdapters.sp_getallattendancesetupTableAdapter();
DataSet4.sp_getallattendancesetupDataTable DS1 = TA1.GetData();
if (DS1.Rows.Count == 0)
{
employee = employee + lstbox.Items[i].Text + ",";
}
else if (DS1.Rows.Count > 0)
{
foreach (DataRow dr in DS1.Rows)
{
foreach (string category in dr["fldemployee"].ToString().Split(','))
{
if (category != "")
{
if (category == id)
{
Value = Value + lstbox.Items[i].Text + "\\n";
break;
}
}
continue;
}
}
}
}
You can use the DataSet's Select() method:
DataRow[] foundRows;
foundRows = dataSet1.Tables["MyTable"].Select("fldempname = 'Hari'");
I haven't worked with datasets in a while.. so there prob is cleaner/better way to do this..
DataSet st = new DataSet();
foreach (DataRow row in st.Tables["table_name"].Rows)
{
if (row["column_name"] == "value")
{
//found
}
}
side note: i'd try Mitch Wheat's answer

Populate DataTable with LINQ in C#

I have a method in my app that populates DataTable with the data using the following code:
DataTable dt = this.attachmentsDataSet.Tables["Attachments"];
foreach (Outlook.Attachment attachment in this.mailItem.Attachments)
{
DataRow dr = dt.NewRow();
dr["Index"] = attachment.Index;
dr["DisplayName"] = String.Format(
CultureInfo.InvariantCulture,
"{0} ({1})",
attachment.FileName,
FormatSize(attachment.Size));
dr["Name"] = attachment.FileName;
dr["Size"] = attachment.Size;
dt.Rows.Add(dr);
}
I was wondering if I could achieve the same functionality using LINQ in order to shorten this code a bit. Any ideas?
Yes, Easy
public void FillFromList(List<T> col)
{
Type elementType = typeof(T);
// Nested query of generic element list of property
// values (using a join to the DataTable columns)
var rows = from row in col
select new
{
Fields = from column in m_dataTable.Columns.Cast<DataColumn>()
join prop in elementType.GetProperties()
on column.Caption equals prop.Name
select prop.GetValue(row, null)
};
// Add each row to the DataTable
int recordCount = 0;
foreach ( var entry in rows )
{
m_dataTable.Rows.Add(entry.Fields.ToArray());
}
This assumes that the properties on T are the same as the DataTable columns.
Well this code isnt shorter or Linq but I did an externsion method that takes a IList and turns it into a DataTable for you.
public static DataTable ToDataTable<T>(this IList<T> theList)
{
DataTable theTable = CreateTable<T>();
Type theEntityType = typeof(T);
// Use reflection to get the properties of the generic type (T)
PropertyDescriptorCollection theProperties = TypeDescriptor.GetProperties(theEntityType);
// Loop through each generic item in the list
foreach (T theItem in theList)
{
DataRow theRow = theTable.NewRow();
// Loop through all the properties
foreach (PropertyDescriptor theProperty in theProperties)
{
// Retrieve the value and check to see if it is null
object thePropertyValue = theProperty.GetValue(theItem);
if (null == thePropertyValue)
{
// The value is null, so we need special treatment, because a DataTable does not like null, but is okay with DBNull.Value
theRow[theProperty.Name] = DBNull.Value;
}
else
{
// No problem, just slap the value in
theRow[theProperty.Name] = theProperty.GetValue(theItem);
}
}
theTable.Rows.Add(theRow);
}
return theTable;
}
You first identify whether you can query this.mailItem.Attachments and
if it is possible, you can convert query result to a datatable from extension method create by Steve Sloka...

How to iterate through a DataTable

I need to iterate through a DataTable. I have an column there named ImagePath.
When I am using DataReader I do it this way:
SqlDataReader dr = null;
dr = cmd.ExecuteReader();
while (dr.Read())
{
TextBox1.Text = dr["ImagePath"].ToString();
}
How can I achieve the same thing using DataTable?
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
foreach(DataRow row in dt.Rows)
{
TextBox1.Text = row["ImagePath"].ToString();
}
...assumes the connection is open and the command is set up properly. I also didn't check the syntax, but it should give you the idea.
foreach (DataRow row in myDataTable.Rows)
{
Console.WriteLine(row["ImagePath"]);
}
I am writing this from memory.
Hope this gives you enough hint to understand the object model.
DataTable -> DataRowCollection -> DataRow (which one can use & look for column contents for that row, either using columnName or ordinal).
-> = contains.
You can also use linq extensions for DataSets:
var imagePaths = dt.AsEnumerble().Select(r => r.Field<string>("ImagePath");
foreach(string imgPath in imagePaths)
{
TextBox1.Text = imgPath;
}
There are already nice solution has been given. The below code can help others to query over datatable and get the value of each row of the datatable for the ImagePath column.
for (int i = 0; i < dataTable.Rows.Count; i++)
{
var theUrl = dataTable.Rows[i]["ImagePath"].ToString();
}
The above examples are quite helpful. But, if we want to check if a particular row is having a particular value or not. If yes then delete and break and in case of no value found straight throw error. Below code works:
foreach (DataRow row in dtData.Rows)
{
if (row["Column_name"].ToString() == txtBox.Text)
{
// Getting the sequence number from the textbox.
string strName1 = txtRowDeletion.Text;
// Creating the SqlCommand object to access the stored procedure
// used to get the data for the grid.
string strDeleteData = "Sp_name";
SqlCommand cmdDeleteData = new SqlCommand(strDeleteData, conn);
cmdDeleteData.CommandType = System.Data.CommandType.StoredProcedure;
// Running the query.
conn.Open();
cmdDeleteData.ExecuteNonQuery();
conn.Close();
GetData();
dtData = (DataTable)Session["GetData"];
BindGrid(dtData);
lblMsgForDeletion.Text = "The row successfully deleted !!" + txtRowDeletion.Text;
txtRowDeletion.Text = "";
break;
}
else
{
lblMsgForDeletion.Text = "The row is not present ";
}
}
foreach(DataGridViewRow row in dataGridView1){ var a = row.Cells[4].Value.ToString(); }

Categories