Not able to read a DataTableReader inside another DataTableReader - c#

Friends expecting ur suggetions to the below code. Instead of taking dtr1( DatatableReader) it is taking outside loop dtr(DataTableReader) Table.
protected void GetStudReport(Object o, EventArgs e)
{
if (mycon.State != ConnectionState.Open)
{
List<string> lstQstn = new List<string>();
mycon.Open();
cmd = new MySqlCommand("SELECT * from scord_mark_table where stu_ID='" + drpDnSearch3.SelectedValue + "'", mycon);
MySqlDataReader rdr1=cmd.ExecuteReader();
DataSet ds=new DataSet();
DataTable dtScrTbl=new DataTable();
dtScrTbl.Load(rdr1);
ds.Tables.Add(dtScrTbl);
rdr1.Close();
cmd = null;
int i = 0;
Dictionary<string, string> dctSub = new Dictionary<string, string>();
**using (DataTableReader dtr = ds.CreateDataReader())**
{
while (dtr.Read())
{
lstQstn.Add(dtr["test_id"].ToString());
while (i <= lstQstn.Count())
{
MySqlCommand cmd2 = new MySqlCommand("SELECT test_id,subject_id from qution_no_table where test_id='" + lstQstn[i].ToString() + "'", mycon);
MySqlDataReader rdr2 = cmd2.ExecuteReader();
DataTable dtQsNoTbl = new DataTable();
dtQsNoTbl.Load(rdr2);
ds.Tables.Add(dtQsNoTbl);
**using (DataTableReader dtr1 = ds.CreateDataReader())**
{
while (dtr1.Read())
{
dctSub.Add(dtr1["test_id"].ToString(), dtr1["subject_id"].ToString()); // **here it is taking table scord_mark_table instead of dtr1's qution_no_table**
}
rdr2.Close();
break;
}
}
//cmd2 = null;
i++;
}
}

No, it's not - it's returning a new DataTableReader hooked to ALL of the existing tables (including the one you created before the first loop).
Try specifying the DataTable you want the readers attached to:
using (DataTableReader dtr = ds.CreateDataReader(dtScrTbl))
and
using (DataTableReader dtr1 = ds.CreateDataReader(dtQsNoTbl))

Related

combobox Selected Text changed event not firing

This is my code. After adding data through DataSource, The SelectedIndexChanged event is not firing.
try
{
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
//comboBox1.Items.Clear();
comboBox1.ResetText();
Cn.Open();
SqlCommand Cd = new SqlCommand("Select Distinct Mobile From Client_Details Where Branch = '" + label2.Text + "'", Cn);
SqlDataReader da = Cd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Mobile", typeof(string));
dt.Load(da);
comboBox1.DisplayMember = "Mobile";
comboBox1.DataSource = dt;
comboBox1.SelectedItem = "<Select>";
}
catch
{
}
finally
{
Cn.Close();
Clear();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//Label CBSL = new Label();
//string CBSL = this.comboBox1.SelectedItem.ToString();
if (comboBox9.Text == "Client")
{
Update_Read_Client();
}
else if (comboBox9.Text == "Customer")
{
Update_Read();
}
}
It selects the first value again and again.
I had tried DropDownStye = DropDownList., But it become dormant. No values is added.
Any help to resolve my problem.
I'm not sure if you have "< Select >" item saved in your database. Also, when using DataTable it's easier to fill it using SqlDataAdapter. You should also use parameters instead of string concat when you're writing your query like this and using keyword closes your connection automatically when you're done using it. I'd write it like this probably:
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"SELECT DISTINCT Mobile
FROM Client_Details
WHERE Branch = #Branch";
cmd.Parameters.AddWithValue("#Branch", label2.Text);
try
{
var dt = new DataTable();
dt.Columns.Add("Mobile", typeof(string));
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
DataRow row = dt.NewRow();
row["Mobile"] = "<Select>";
dt.Rows.InsertAt(row, 0);
comboBox1.DisplayMember = "Mobile";
comboBox1.DataSource = dt;
comboBox1.SelectedItem = "<Select>";
}
catch
{
throw;
}
}

using dropdown menu sql statement not working

protected void btn_search_Click(object sender, EventArgs e)
{
using (con = new SqlConnection(CS))
{
string _var_search = ddl_search_by.SelectedItem.Text;
string _var_by = ddl_search.SelectedItem.Text;
cmd = new SqlCommand("Select * from UserProfile Where '"+_var_search+"'='" + _var_by + "'", con);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
Repeater1.DataSource = ds.Tables[0];
Repeater1.DataBind();
if (ds.Tables[0].Rows.Count > 0)
{
txt_not_found.Visible = false;
}
else
{
txt_not_found.Visible = true;
}
}
}
dont use quotes in first parameter:
cmd = new SqlCommand("Select * from UserProfile Where "+_var_search+"='" + _var_by + "'", con);
even better use paramaters:
cmd = new SqlCommand("Select * from UserProfile Where "+_var_search+"=#param", con);
cmd.Parameters.AddWithValue("#param", _var_by);

How to Display Warning message if quantity is less than 5 items

I'm creating an inventory system which should display the products that needs to be restock. If the quantity of the product is only 5 it should display a message that says you need to restock now. But I don't know how to do that because I'm creating an Inventory System only and not Sales and Inventory so how should I deduct it if I don't have sales system? I'm sorry, hope u guys understand.
Here is my code:
public void all()
{
SqlConnection MySqlConnection;
DataTable p_table = new DataTable();
MySqlConnection = new SqlConnection("Data Source=christina\\sqlexpress;Initial Catalog=cafe_inventory;User ID=sa;Password=tina;");
MySqlConnection.Open();
SqlCommand command1 = new SqlCommand("Select * from inventory", MySqlConnection);
//Clear the datatable to prevent duplicate generation of data in gridview.
p_table.Clear();
SqlDataAdapter m_da = new SqlDataAdapter("Select * from inventory", MySqlConnection);
//DataSet ds = new DataSet();
//DataTable dtable = ds.Tables["empinfo1"];
m_da.Fill(p_table);
// Clear the ListView control
//listView3.Items.Clear();
// Display items in the ListView control
for (int i = 0; i < p_table.Rows.Count; i++)
{
DataRow drow = p_table.Rows[i];
// Only row that have not been deleted
if (drow.RowState != DataRowState.Deleted)
{
// Define the list items
//(drow["bnum"].ToString());
ListViewItem lvi = new ListViewItem(drow["pnum"].ToString());
lvi.SubItems.Add(drow["pname"].ToString());
lvi.SubItems.Add(drow["descr"].ToString());
lvi.SubItems.Add(((DateTime)drow["dater"]).ToShortDateString());
//lvi.SubItems.Add(drow["exp"].ToString());
lvi.SubItems.Add(((DateTime)drow["exp"]).ToShortDateString());
lvi.SubItems.Add(drow["qt"].ToString());
// Add the list items to the ListView
listView2.Items.Add(lvi);
}
}
}
edited code:
public void stock()
{
SqlConnection MySqlConnection;
DataTable p_table = new DataTable();
MySqlConnection = new SqlConnection("Data Source=christina\\sqlexpress;Initial Catalog=cafe_inventory;User ID=sa;Password=tina;");
MySqlConnection.Open();
SqlCommand command1 = new SqlCommand("Select pname from inventory where qt < 5", MySqlConnection);
//Clear the datatable to prevent duplicate generation of data in gridview.
p_table.Clear();
SqlDataAdapter m_da = new SqlDataAdapter("Select pname from inventory where qt < 5", MySqlConnection);
m_da.Fill(p_table);
SqlDataReader reader;
reader = command1.ExecuteReader();
StringBuilder productNames = new StringBuilder();
while (reader.Read())
{
productNames.Append(reader["pname"].ToString() + Environment.NewLine);
}
MySqlConnection.Close();
MessageBox.Show("There are products that needs restocking, check to restock now." + productNames);
// Display items in the ListView control
for (int i = 0; i < p_table.Rows.Count; i++)
{
DataRow drow = p_table.Rows[i];
// Only row that have not been deleted
if (drow.RowState != DataRowState.Deleted)
{
// Define the list items
//ListViewItem lvi = new ListViewItem(drow["bnum"].ToString());
ListViewItem lvi = new ListViewItem(drow["pnum"].ToString());
lvi.SubItems.Add(drow["pname"].ToString());
lvi.SubItems.Add(drow["descr"].ToString());
lvi.SubItems.Add(((DateTime)drow["dater"]).ToShortDateString());
//lvi.SubItems.Add(drow["exp"].ToString());
lvi.SubItems.Add(((DateTime)drow["exp"]).ToShortDateString());
lvi.SubItems.Add(drow["qt"].ToString());
lvi.SubItems.Add(drow["interval"].ToString());
// Add the list items to the ListView
listView4.Items.Add(lvi);
}
}
}
Try This:
void DisplayLowQuantityItems()
{
MySqlConnection con = new MySqlConnection("Data Source=christina\\sqlexpress;
Initial Catalog=cafe_inventory;User ID=sa;Password=tina;");
MySqlCommand command = new MySqlCommand("Select pname from inventory
where qt < 5", con);
con.Open();
MySqlDataReader reader = commad.ExecuteReader();
StringBuilder productNames= new StringBuilder();
while(reader.Read())
{
productNames.Append(reader["pname"].ToString()+Environment.NewLine);
}
con.Close();
MessageBox.Show("Following Products quantity is lessthan 5\n"+productNames);
}
Solution 2:
edited code:
public void stock()
{
MySqlConnection con;
DataTable p_table = new DataTable();
con = new MySqlConnection("Data Source=christina\\sqlexpress;Initial
Catalog=cafe_inventory;User ID=sa;Password=tina;");
con.Open();
MySqlCommand command1 = new MySqlCommand("Select pname from inventory where
qt < 5", con);
//Clear the datatable to prevent duplicate generation of data in gridview.
p_table.Clear();
MySqlDataAdapter m_da = new MySqlDataAdapter("Select * from inventory where
qt < 5", con);
m_da.Fill(p_table);
MySqlDataReader reader;
reader = command1.ExecuteReader();
StringBuilder productNames = new StringBuilder();
while (reader.Read())
{
productNames.Append(reader["pname"].ToString() + Environment.NewLine);
}
con.Close();
MessageBox.Show("There are products that needs restocking,
check to restock now." + productNames);
// Display items in the ListView control
for (int i = 0; i < p_table.Rows.Count; i++)
{
DataRow drow = p_table.Rows[i];
// Only row that have not been deleted
if (drow.RowState != DataRowState.Deleted)
{
// Define the list items
//ListViewItem lvi = new ListViewItem(drow["bnum"].ToString());
ListViewItem lvi = new ListViewItem(drow["pnum"].ToString());
lvi.SubItems.Add(drow["pname"].ToString());
lvi.SubItems.Add(drow["descr"].ToString());
lvi.SubItems.Add(((DateTime)drow["dater"]).ToShortDateString());
//lvi.SubItems.Add(drow["exp"].ToString());
lvi.SubItems.Add(((DateTime)drow["exp"]).ToShortDateString());
lvi.SubItems.Add(drow["qt"].ToString());
lvi.SubItems.Add(drow["interval"].ToString());
// Add the list items to the ListView
listView4.Items.Add(lvi);
}
}
}
another way of checking your data
DataTable p_table = new DataTable();
con = new MySqlConnection("Data Source=christina\\sqlexpress;Initial
Catalog=cafe_inventory;User ID=sa;Password=tina;");
con.Open();
MySqlCommand command1 = new MySqlCommand("Select pname from inventory where
qt < 5", con);
p_table.load(command1.ExecuteReader());

using WHERE in my Insert query statement

string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\user\Documents\Visual Studio 2010\Projects\Timetable\Timetable\bin\Debug\timetabledata.accdb";
//create the database query
string query = "SELECT * FROM relation";
OleDbConnection conn = new OleDbConnection(conString);
conn.Open();
// create the DataSet
DataSet ds = new DataSet();
// create the adapter and fill the DataSet
OleDbDataAdapter adapter;
adapter = new OleDbDataAdapter(query, conn);
adapter.Fill(ds);
int f = ds.Tables[0].Rows.Count;
int i;
for (i = 0; i < f; i++)
{
// create the database query
string query1 = "SELECT * FROM [time] Where classid= '"+
ds.Tables[0].Rows[i].ItemArray[2]+"'";
DataSet ds1 = new DataSet();
OleDbDataAdapter adapter1;
adapter1 = new OleDbDataAdapter(query1, conn);
adapter1.Fill(ds1);
MessageBox.Show(ds1.Tables[0].Rows[0].ItemArray[0].ToString());
}
the result that i get not true in message box that i want the id of all rows having the same classid but in message box that i use just to verification before o continue i see the id of time table without be consider where
Shouldn't this part be changed from...
string query1 = "SELECT * FROM [time] Where classid+ '"+
ds.Tables[0].Rows[i].ItemArray[2]+"'";
to...
string query1 = "SELECT * FROM [time] Where classid = '"+
ds.Tables[0].Rows[i].ItemArray[2]+"'";
You seem to be using a plus symbol (+) instead of equals (=).
Give this a shot:
public DataSet GetRelations()
{
using (var connection = new OleDbConnection(ConnectionString))
{
connection.Open();
using (var adapter = new OleDbDataAdapter("SELECT * FROM [relation]", connection))
{
var results = new DataSet();
adapter.Fill(results);
return results;
}
}
}
public DataSet GetTimeResults()
{
DataSet dsRelations = GetRelations();
var dsResults = new DataSet();
using (var connection = new OleDbConnection(ConnectionString))
{
connection.Open();
foreach (DataRow row in dsRelations.Tables[0].Rows)
{
using (var command = new OleDbCommand("SELECT * FROM [time] Where classid = ?", connection))
{
// not entirey sure what the value of row.ItemArray[2] is ?
command.Parameters.Add(row.ItemArray[2]);
using (var adapter = new OleDbDataAdapter(command))
{
adapter.Fill(dsResults);
}
}
}
}
return dsResults;
}
Just invoke it and use it as you see fit:
public void Test()
{
DataSet dsTimeResults = GetTimeResults();
// Do whatever you need with the results
}

How to assign 3 values into a single string

I have an issue with assigning values.
string userlanguages = string.Empty;
try
{
SqlCommand cmd = new SqlCommand("SELECT [s_langName] from [dbo].[tx_UserLanguages] WHERE [s_ID] ='" + Class1.EmployeeId + "'", objcon);
if (objcon.State == ConnectionState.Closed) objcon.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet myDS = new DataSet();
adp.Fill(myDS);
userlanguages = myDS.Tables[0].Rows[0]["[s_langName]"].ToString();
}
catch (SqlException exc)
{
Response.Write(exc.Message);
}
finally
{
objcon.Close();
Class1.langKnwn = userlanguages;
}
}
Suppose, Here the myDs contains three values. Then how will i assign them to a single string(in this case 'userlanguages'). I am using the Class1.langKnwn in another page to display the user selected languages(which may be more than 1 language in many cases).
Please help me.
How about somethig like
List<string> languages = new List<string>();
for (int iRow = 0; iRow < myDS.Tables[0].Rows.Count; iRow++)
languages.Add(myDS.Tables[0].Rows[iRow]["[s_langName]"].ToString());
userlanguages = String.Join(",", languages);
SqlCommand cmd = new SqlCommand("SELECT [s_langName] from [dbo].[tx_UserLanguages] WHERE [s_ID] ='" + Class1.EmployeeId + "'", objcon);
if (objcon.State == ConnectionState.Closed) objcon.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet myDS = new DataSet();
adp.Fill(myDS);
for(int ndx=0;ndx<myDS.Tables[0].Rows.Count;ndx+=1)
{
if(ndx==0)
{
userlanguages = myDS.Tables[0].Rows[ndx]["[s_langName]"].ToString();
}
else
{
userlanguages = userlanguages+","+ myDS.Tables[0].Rows[ndx]["[s_langName]"].ToString();
}
}
userlanguages = string.Join(",", myDS.Tables[0].AsEnumerable()
.Select(row => row.Field<string>("[s_langName]"))
.ToArray());
If I understand your question correctly, using SqlDataReader could be better option in your case.
using (SqlConnection objcon= new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SELECT [s_langName] from [dbo].[tx_UserLanguages] WHERE [s_ID] = #id", objcon);
cmd.Parameters.AddWithValue("#id", Class1.EmployeeId);
connection.Open();
SqlDataReader reader = cmd .ExecuteReader();
string userlanguages = string.Empty;
while (reader.Read())
{
string str = reader.GetString(0);
userlanguages = String.Join(",", userlanguages);
}
reader.Close();
}
And you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Try this
Use using System.Text; namesapce
and then write that code in your block
StringBuilder sb = new StringBuilder();
for (int iRow = 0; iRow < myDS.Tables[0].Rows.Count; iRow++)
{
sb.Append(myDS.Tables[0].Rows[iRow]["[s_langName]"].ToString());
sb.Append(",");
}
// to get the string at the end
string myString = sb.ToString();
myString= myString.Substring(0, myString.Length - 1);

Categories

Resources