mysql select query skipping first row values - c#

There is only a drop down list with student ID and a grid view with students' images in my web page.
If I select a student Grid View has to show all the images of the selected student.
Problem is when I select a student my grid view is skipping first two values.
I mean if there are 6 images grid view shows only 4 images.
Here is my code:
private void BindGrid()
{
MySqlConnection con = new MySqlConnection(constr);
MySqlCommand cmd = new MySqlCommand("SELECT * FROM images where Image_ID in (" + String.Join(",", getImage_ID()) + ")", con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
gvImages.DataSource = dt;
gvImages.DataBind();
}
private List<int> getImage_ID()
{
List<int> i = new List<int>();
MySqlConnection con = new MySqlConnection(constr);
con.Open();
string query = "Select Come_Image_ID1, Leave_Image_ID from register where Students_ID='" + getStudents_ID() + "' AND Come_Image_ID IS NOT NULL AND Leave_Image_ID IS NOT NULL";
MySqlCommand cmd = new MySqlCommand(query);
cmd.Connection = con;
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
foreach (DbDataRecord s in reader)
{
i.Add(s.GetInt32(0));
i.Add(s.GetInt32(1));
}
}
reader.Close();
return i;
}
What is the best coding practice for this issue?

You are mixing ways to read data. Either you a while loop:
while (reader.Read())
{
i.Add(reader.GetInt32(0));
i.Add(reader.GetInt32(1));
}
Or a foreach loop:
foreach (DbDataRecord s in reader)
{
i.Add(s.GetInt32(0));
i.Add(s.GetInt32(1));
}
But not both.
Both the while and the foreach consume records from the cursor, and when you mix them like this you skip the records the while loop consumes.

Related

How to use stored procedure result as a sub query in C#

I have a C# code that executes the SQL query. The input of the SQL query comes from a result of a stored procedure. The stored procedure returns a table 6 columns and 25,000 rows. I want to use this stored procedure result as an input to the SQL query. I am storing the stored procedure result in a DataSet. It looks like it's not the correct way to add DataSet results in the query. I need help here experts
Here is what I am doing.
public static void ExecuteSQLQueryTest(string qryName, Boolean nestedQry, string spName)
{
DataTable dtLocalResult = new DataTable();
DataTable dtAzurelResult = new DataTable();
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
List<string> lstring = new List<string>();
aadSQLConnection.Open();
//Connection to CPDashboard DB
var cpdbconnection = new SqlConnection(ConfigurationManager.ConnectionStrings["CATSQL"].ConnectionString);
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = cpdbconnection;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = spName;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
string qryName = "Update A SET A.Environment = B.SC_MD_Environment, A.OSImage = B.SC_APMD_OSImage FROM" + dt + " A"
+ "INNER JOIN[CLOUD].cloudsql.caa.aa_AT_S B ON A.ServerName = B.SC_APMD_MachineName";
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = aadSQLConnection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = qryName;
using (SqlDataAdapter daa = new SqlDataAdapter(cmd))
{
daa.Fill(dt1);
}
}
}
Accessing cell value of your DataTable should be in this format
dt[row index][col index]
And also, we need to put space in between your Table and From
string qryName = "Update A SET A.Environment = B.SC_MD_Environment, A.OSImage = B.SC_APMD_OSImage "
+ "FROM " + dt[0][0] + " A"
+ "INNER JOIN[CLOUD].cloudsql.caa.aa_AT_S B ON A.ServerName = B.SC_APMD_MachineName";
If you are trying to update your datatable from your stored procedure output. you need to use select query for your cloud table instead, then update your datatable.
foreach(DataRow row in dt.Rows)
{
string qryName = "select Environment from [CLOUD].cloudsql.caa.aa_AT_S B where A.ServerName = '"+row["ServerName"].ToString()+"'";
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = aadSQLConnection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = qryName;
using (SqlDataAdapter daa = new SqlDataAdapter(cmd))
{
.....update your datable here
}
}
}

How to display the proper data?

I have 2 datagridviews now i want to select a column named "Name" in the first datagridview and us it as the WHERE in my query to Select values from a table and put it in the other datagridview.
SqlCommand cmd = new SqlCommand();
cmd = ss.CreateCommand();
foreach (DataGridViewRow row in dgvAtt.Rows)
{
ss.Open();
cmd.CommandType = CommandType.Text;
string Query = "SELECT Signature FROM TBL_Student WHERE Name = '" +
row.Cells[4].Value.ToString() + "' ";
cmd.CommandText = Query;
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter dp = new SqlDataAdapter(cmd);
dp.Fill(dt);
dgvSign.DataSource = dt;
ss.Close();
}
but it gives me error when there is null and it is only selecting the first row in the first datagridview.
You create in each foreach-loop a new DataTable and therefore it will always just have one Value. So you have to create it before the foreach-loop.
And make sure you check the Values you want to use before using them.
With this easy if-condition, there won't be any problems.
Edit1:
This code snippet is working just fine.
Just change the ConnectionString and you are done.
DataTable dt = new DataTable();
string error;
using (SqlConnection con = new SqlConnection(#"Data Source=SERVER;Initial Catalog=DATEBASE; User ID=USERNAME; Password=PASSWORD"))
{
SqlCommand cmd = new SqlCommand();
foreach (DataGridViewRow row in dgvAtt.Rows)
{
string Query = "SELECT Signature FROM TBL_Student WHERE Name = '";
if (row.Cells.Count >= 4 && row.Cells[4].Value != null)
{
Query += row.Cells[4].Value.ToString();
}
Query += "'";
try
{
cmd = new SqlCommand(Query, con);
if (con.State == ConnectionState.Closed)
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
}
catch (Exception ex)
{
error = ex.Message;
}
}
}
dgvSign.DataSource = dt;

search Datagridview by using multiple checkedlistbox c#

how can i search data by chekced multiple checkedlistbox when clicking search..?
How can I accomplish filtering data by multiple checkedlistboxes when clicking search?
For example I want to search data that has penyakit = 'Penyakit B' and placeholder = '07'. So when I click search, it should show one row that matches both of these conditions
Here is what I have so far:
MySqlConnection con = new MySqlConnection(MyConnectionString);
con.Open();
try
{
MySqlCommand cmd = con.CreateCommand();
foreach (object itemChecked in chkboxPenyakit.CheckedItems)
{
cmd.CommandText = "Select * FROM tb_pasien where Penyakit = '" + itemChecked.ToString() + "'";
}
MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
dgvData.DataSource = ds.Tables[0].DefaultView;
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Clone();
}
}

C# asp.net Create multiple check box dynamically with value of mysql database

i am trying to create multiple check box with the value of mysql database fetched rows say for me if i have 10 rows in DB i need 10 check box to be created dynamically in a div.
am not sure how to do that but i have done a slimier code which add's a "," after each fetch.
string constr = ConfigurationManager.ConnectionStrings["ConnectionStrings"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand MySqlCommand = new MySqlCommand("SELECT FatherFullName FROM xxxxxx where sssss='xxxxx'", con))
{
MySqlCommand.CommandType = CommandType.Text;
con.Open();
MySqlDataReader MySqlDataReader = MySqlCommand.ExecuteReader();
var list = new List<string>();
while (MySqlDataReader.Read())
{
string name = MySqlDataReader["FatherFullName"].ToString();
if (!String.IsNullOrEmpty(name))
list.Add(name);
}
con.Close();
}
}
I will suggest use asp.net CheckBoxList Control, Suppose its name is CheckBoxList1 then Declare Datatable and get the data to be bind in that datatables Object
using (MySqlCommand MySqlCommand = new MySqlCommand("SELECT FatherFullName FROM xxxxxx where sssss='xxxxx'", con))
{
MySqlCommand.CommandType = CommandType.Text;
con.Open();
DataTable dt = MySqlCommand.ExecuteTable();
if(dt.Rows.Count > 0)
{
CheckBoxList1.DataSource = dt;
CheckBoxList1.DataTextField = "Title";
CheckBoxList1.DataValueField = "ArticleID";
CheckBoxList1.DataBind();
}
con.Close();
}

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());

Categories

Resources