How to use the Columns of dataset - c#

I have a result set of dataset like below
[![Dataset][1]][1]
Now I want to add the IF condition for checking like below
if(dataset rows(Usermail) == 10000){then go ahead}
this is my code.
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"].ToString()))
{
SqlCommand sqlComm = new SqlCommand("GET_INWARD_REMINDER_REPORT", conn);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
if(DataSet rowchecking)
{
}
}
So my issue, how to check and compare dataset columns.

You can do it like below:
int First = Convert.ToInt32(ds.Tables[0].Rows[0]["columnName1"].ToString());
string Second = ds.Tables[0].Rows[0]["columnName2"].ToString();
So for your case it can be like:
foreach (DataRow dr in ds.Tables[0].Rows)
{
if(dr["UserEmail"].ToString() == "10000")
{
//do something;
}
}

You can use a foreach to loop the rows and use DataRow.Field to get the email:
foreach(DataRow row in ds.Tables[0].Rows)
{
if(row.Field<string>("UserEmail") == "10000")
continue; // or revert it and do something if UserEmail != "1000"
}

After Fill dataset.
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if(ds.Tables[0].Rows[i]["UserEmail"].ToString() == "10000")
{
//do something;
}
}
}

Related

Trying to return records from database using c#

This is my code which i'm trying to return records back into a listview by entering different ID's. But i only seem to get the first record back no matter which ID i enter. Any help would be appreciated.
private void FindRecord()
{
List<SprocParameter> paramsSQL = new List<SprocParameter>();
paramsSQL.Add(new SprocParameter("ID", textBoxID.Text) );
DataSet ds = StoredProcedureExecute("get_ID", paramsSQL );
if (null != ds && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
textBoxID.Text = ds.Tables[0].Rows[0]["ID"].ToString();
textBoxName.Text = ds.Tables[0].Rows[0]["Name"].ToString();
textBoxAddress.Text = ds.Tables[0].Rows[0]
["Address"].ToString();
textBoxPhone.Text = ds.Tables[0].Rows[0]["Phone"].ToString();
}
else
{
textBoxID.Text = "Unrecognised ID";
textBoxName.Text = "Incorrect Name";
textBoxAddress.Text = "Wrong Address";
textBoxPhone.Text = "Invalid Number";
}
}
You aim is not entirely clear here, as you appear to be asking how to handle multiple rows but assigning these values to a text box which would suggest you only actually want one at a time. May I suggest executing the command stored procedure is a more readable way:
DataSet ds = new DataSet("peopleData");
using(SqlConnection conn = new SqlConnection("ConnectionString"))
{
SqlCommand sqlComm = new SqlCommand("get_ID", conn);
sqlComm.Parameters.AddWithValue("#ID", textBoxID.Text);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
Then the data can be accessed with something like this for a single row outputting to a textbox:
DataRow dr = ds.Tables[0].Rows[0]; // This will access the first row
textBoxName.Text = dr["Name"].ToString();
Or if you are expecting your stored procedure to return many rows, you can iterate through them by doing something like the below. Although, in this case I suspect you wouldn't want to assign each value directly to the textbox, so it may be more appropriate deploy a ListView as suggested in the comments.:
foreach (DataTable dt in ds.Tables) // Only if you're expecting many datatables.
{
foreach (DataRow dr in dt.Rows)
{
textBoxName.Text = dr["Name"].ToString();
}
}

how to display the datavaluefield of selected items in different listbox in asp.net

I have 3 listboxes.The listbox fetches two values by code-datatextfield and datavaluefield. 1st listbox transfers the datatextfield items from 1st listbox to 2nd listbox.i want to transfer the datavaluefield of selected 1st listbox items to 3rd listbox.
if (ListBox3.SelectedIndex >= 0
{
for (int i = 0; i < ListBox3.Items.Count; i++)
{
if (ListBox3.Items[i].Selected)
{
if (!arraylist1.Contains(ListBox3.Items[i]))
{
arraylist1.Add(ListBox3.Items[i]);
Session["value"] = ListBox3.Items[i];
}
}
}
for (int i = 0; i < arraylist1.Count; i++)
{
if (!ListBox2.Items.Contains(((ListItem)arraylist1[i])))
{
ListBox2.Items.Add(((ListItem)arraylist1[i]));
}
ListBox3.Items.Remove(((ListItem)arraylist1[i]));
}
ListBox2.SelectedIndex = -1;
}
else
{
}
SqlConnection con = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("select * from IT_1_BOILER_DESK_1_PARAMETERS where paramtext='" + Session["value"] + "'", con);
SqlDataAdapter dataAadpter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
dataAadpter.Fill(ds);
if (ds != null)
{
ListBox1.DataSource = ds.Tables[0];
ListBox1.DataTextField = "param";
//ListBox3.DataValueField = "param";
ListBox1.DataBind();
}
for listbox 3
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("select * from IT_1_BOILER_DESK_1_PARAMETERS where pname='" + this.DropDownList1.SelectedValue + "'" ,con);
SqlDataAdapter dataAadpter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
dataAadpter.Fill(ds);
if (ds != null)
{
ListBox3.DataSource = ds.Tables[0];
ListBox3.DataTextField = "paramtext";
ListBox3.DataValueField = "param";
ListBox3.DataBind();
}
}
But i want to display the datavaluefield of the items that are selected from listbox3 to listbox1
Since you want to show DataTextField value and DataValueField value from one listbox into 2 different listbox. I suggest you to use a different approach. This will also reduce usage of 2nd database call.
Try following:-
if (ListBox3.SelectedIndex >= 0)
{
for (int i = 0; i < ListBox3.Items.Count; i++)
{
if (ListBox3.Items[i].Selected)
{
if (!arraylist1.Contains(ListBox3.Items[i]))
{
arraylist1.Add(ListBox3.Items[i]);
//Session["value"] = ListBox3.Items[i]; no need of this
}
}
}
for (int i = 0; i < arraylist1.Count; i++)
{
if (ListBox2.Items.FindByText(((ListItem)arraylist1[i]).Text)==null)
{
//since you already have text and value field values in arrayList. Use them
ListBox2.Items.Add(new ListItem(((ListItem)arraylist1[i]).Text));
}
if (ListBox1.Items.FindByText(((ListItem)arraylist1[i]).Text)==null)
{
ListBox1.Items.Add(new ListItem((ListItem)arraylist1[i]).Value));
}
ListBox3.Items.Remove(((ListItem)arraylist1[i]));
}
ListBox2.SelectedIndex = -1;
}
else
{
}
/* This database call can be removed
SqlConnection con = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("select * from IT_1_BOILER_DESK_1_PARAMETERS where paramtext='" + Session["value"] + "'", con);
SqlDataAdapter dataAadpter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
dataAadpter.Fill(ds);
if (ds != null)
{
ListBox1.DataSource = ds.Tables[0];
ListBox1.DataTextField = "param";
//ListBox3.DataValueField = "param";
ListBox1.DataBind();
}*/

Setting value to ComboBoxs item #C

I'm trying to set values on items in combobox, but everytime I try so I get the result 'null'. Am I defining the value wrong or am I trying to get the value in a wrong way?
// Setting the value
sqlCmd.CommandText = "SELECT Id, Ime FROM Unajmljivaci WHERE Aktivan = 0";
conn.Open();
using (var reader = sqlCmd.ExecuteReader())
{
while (reader.Read())
{
cmbUnajmljivaci.Items.Add(new { Id = reader["Id"].ToString(), Ime = reader["Ime"].ToString() });
}
cmbUnajmljivaci.ValueMember = "Id"; // <---
cmbUnajmljivaci.DisplayMember = "Ime";
}
//Retrieving the value
sqlCmd.Parameters.AddWithValue("#SifraUnajmljivca", Convert.ToString(cmbUnajmljivaci.SelectedValue));
using (SqlConnection sqlConn = new SqlConnection("CONNECTION STRING"))
{
DataSet ds = new DataSet();
SqlCommand sqlCmd = sqlConn.CreateCommand();
sqlConn.Open();
SqlDataAdapter SQA_DataAdapter = new SqlDataAdapter(sqlCmd);
SQA_DataAdapter.SelectCommand = new SqlCommand("SELECT Id, Ime FROM Unajmljivaci WHERE Aktivan = 0", sqlConn);
SQA_DataAdapter.Fill(ds, "Table");
if (ds != null)
if (ds .Tables.Count > 0)
{
cmbUnajmljivaci.ValueMember = "Id";
cmbUnajmljivaci.DisplayMember = "Ime";
cmbUnajmljivaci.DataSource = ds.Tables[0];
}
sqlConn.Close();
}
You need to set the data source of the combobox.
Try getting the Value like this:
dynamic dyn = cmbUnajmljivaci.SelectedItem;
string s = dyn.Id;
Or even inline like this:
//Retrieving the value
sqlCmd.Parameters.AddWithValue("#SifraUnajmljivca", Convert.ToString(((dynamic)cmbUnajmljivaci.SelectedItem).Id);
Sample Code for Reference to your problem,
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Rows.Add("0", "Item1");
dt.Rows.Add("1", "Item2");
For inserting the item with specified index you need to use the below code
//Insert the item into the collection with specified index
foreach (DataRow row in dt.Rows)
{
int id = Convert.ToInt32(row["ID"]);
string name=row["Name"].ToString();
comboBox1.Items.Insert(id,name);
}
Always index should start from 0 (Zero).
Easy way to add values to combobox
comboBox1.DataSource=dt;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";

ArgumentNullException while dealing with DataTable and DataAdapter in c#

i am using DataAdapter to fill my DataTable with query as Stored Procedure.
But there is an exception ArgumentNullExceptioncoming when i try to Fill DataTable. I tested the query and its working fine.
Here's my code:
if (!IsPostBack)
{
Session["NewsId"] = Convert.ToInt32(Request.QueryString["news"]);
if (Session["NewsId"] != null && Convert.ToInt32(Session["NewsId"]) != 0)
{
id = Convert.ToInt32(Session["NewsId"]);
}
}
da = new SqlDataAdapter("NewsGallerySelect", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("#NewsID", SqlDbType.Int).Value = id;
da.Fill(dt);
if (dt.Rows.Count > 0)
{
rptrNews.DataSource = dt;
rptrNews.DataBind();
foreach (DataRow row in dt.Rows)
{
lblShrtDesc.Text = row["ShortDesc"].ToString();
lblShrtDesc2.Text = row["ShortDesc"].ToString();
lblDesc.Text = row["NewsDesc"].ToString();
lblDesc2.Text = row["NewsDesc"].ToString();
lblDate.Text = row["NewsDate"].ToString();
}
}

Select 2 or more columns on DataTable using LINQ

I have a DataTable and I want to select multiple columns on the DataTable that matches the input in the textbox. The code below only selects 1 column.
var result = from data in mDataTable.AsEnumerable ()
where data.Field<string>("Code") == txtCode.Text
select data.Field<string> ("Description");
foreach (var res in result) {
txtxDescription.Text = res.ToString ();
}
How can I select 2 or more columns on DataTable using LINQ?
why not select full rows (DataRow object) and then take all necessary values from them?
var rows = mDataTable.AsEnumerable()
.Where(data => data.Field<string>("Code") == txtCode.Text);
foreach(DataRow r in rows)
{
txtxDescription.Text = r.Field<string>("Description");
}
another option is to project data to anonymous objects:
var result = from data in mDataTable.AsEnumerable ()
where data.Field<string>("Code") == txtCode.Text
select new
{
Description = data.Field<string> ("Description"),
Code = data.Field<string> ("Code")
};
foreach (var res in result)
{
// last value always replace `txtxDescription.Text` ??
txtxDescription.Text = res.Description;
txtxCode.Text = res.Code;
}
public void GridviewBinding()
{
DataSet ds = new DataSet();
string constr = ConfigurationManager.ConnectionStrings["SQLMSDB"].ConnectionString;
string sql = "select * from tbl_users";
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql))
{
cmd.Connection = conn;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(ds);
gridviewcontrol.DataSource = ds;
gridviewcontrol.DataBind();
ViewState["GridViewBindingData"] = ds.Tables[0];
}
}
}
}
protected void btn_searching_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(txt_search.Text.Trim().ToString()) || !String.IsNullOrWhiteSpace(txt_search.Text.Trim().ToString()))
{
DataTable dt = (DataTable)ViewState["GridViewBindingData"];
var dataRow = dt.AsEnumerable().Where(x => x.Field<dynamic>("UserName") == txt_search.Text);
DataTable dt2 = dataRow.CopyToDataTable<DataRow>();
gridviewcontrol.DataSource = dt2;
gridviewcontrol.DataBind();
}
else
{
GridviewBinding();
}
}

Categories

Resources