Winforms comboboxes and parameterized stored procedure - c#

In my tblSates Table, I have a column named Monat with these three values
[01.2016, 02.2016 and 03.2016] and I want to fetch these values in a combobox.
I am getting the values but just two of them instead of all three.
Here is my code:
private void FillCombobox2()
{
string S = ConfigurationManager
// TSQL-Statement
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = ("SELECT DISTINCT Monat from tblSales");
SqlDataReader myReader;
try
{
con.Open();
myReader = cmd.ExecuteReader();
if (myReader.Read())
{
DataTable dt = new DataTable();
dt.Load(myReader);
combobox1.DisplayMember = "Monat";
combobox1.ValueMember = "Monat";
combobox1.DataSource = dt;
combobox1.SelectedIndex = -1;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
Will appreciate any help or an alternative solution.

I removed reader.Read and then call which advanced the position (and skipped one of my three records). Alternatively I could have used if (myReader.HasRows).
private void FillCombobox2()
{
string S = ConfigurationManager
// TSQL-Statement
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = ("SELECT DISTINCT Monat from tblSales");
//SqlDataReader myReader;
try
{
con.Open();
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
ad.Fill(dt)
combobox1.DisplayMember = "Monat";
combobox1.ValueMember = "Monat";
combobox1.DataSource = dt;
combobox1.SelectedIndex = -1;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}

Related

I am created combobox in datagridview and it retrive the data through database, I want when I run the page combobox shows the default value

I am working on windows application,combo box works perfectly but by default when I run the page ,it shows blank , I want to show the default value.I am using this code.
public void combofill()
{
cmb.Items.Clear();
cmb.Items.Add("select");
SqlConnection con = new SqlConnection(con1);
con.Open();
SqlCommand cmd = new SqlCommand("Select Name from mr000 where Type&0x0f=3", con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
cmb.DataSource = dt;
cmb.Name = "combocust";
cmb.DisplayMember = "Name";
cmb.HeaderText = "Change Customer";
dataGridView1.Columns.Insert(3, cmb);
con.Close();
}
try this code
public void FillCmbo(String Sql, ComboBox cmb, String name)
{
try
{
if (Con.State == ConnectionState.Open)
Con.Close();
Con.Open();
SqlConnection con = new SqlConnection(Sql, Con);
SqlCommand cmd = new SqlCommand("Select Name from mr000 where Type&0x0f=3", con);
DataTable dt = new DataTable();
con.Fill(dr);
dt.Rows.InsertAt(Drw, 0);
cmb.Name = "combocust";
cmb.DisplayMember =name;
cmb.HeaderText = "Change Customer";
cmb.DataSource = dt;
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Check", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
you can also use
ComboBox.selectIndex=0;

How to return default value when value is null or empty

How can I make the below code return zero if the returned value is null or empty. Also how can I return only the first record on the data table
private DataTable GetData(SqlCommand cmd)
{
gridoutofstock.DataBind();
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["AhlhaGowConnString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
You need to use SqlCommand.ExecuteScalar instead of the SqlDataAdapter, you are trying to retrive a single scalar value and not a DataSet.
Example :
static int GetOrderQuantity()
{
int quantity = 0;
string sql = "select sum(Quantity) from [dbo].Orderdetails ";
using (SqlConnection conn = new SqlConnection("Your connection string"))
{
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
quantity = (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
//Handle exception
}
}
return quantity;
}

data not show on ms access

i'm writing a code on c# (winform). the program is about cachier and the database is
ms access.
when i am entering the data to the database it seems like the data was enterd but when i'm opening the ms access the table is empty. althogh, if i right click on the 'preview data set' in the visual studio, i can see the data.
here is my code so far regard to the database:
private void buttonCloseCart_Click(object sender, EventArgs e)
{
for (int i = 0; i < baught_items.Count; i++)
{
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\אורון\documents\visual studio 2012\Projects\CachierPro\CachierPro\CachierProDB.accdb";
string temp_item = baught_items[i].ToString();
int temp_item_quantity = baught_items_quantity[i];
double temp_item_price = baught_items_price[i];
double temp_total_item_price = total_items_price[i];
connect.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO Receipts (ItemName, Quantity, PricePerOne, Total) VALUES (#temp_item, #temp_item_quantity, #temp_item_price, #temp_total_item_price)", connect);
if (connect.State == ConnectionState.Open)
{
cmd.Parameters.Add ("#temp_item", OleDbType.Char, 20).Value = temp_item;
cmd.Parameters.Add("#temp_item_quantity", OleDbType.Integer, 20).Value = temp_item_quantity;
cmd.Parameters.Add("#temp_item_price", OleDbType.Double, 20).Value = temp_item_price;
cmd.Parameters.Add("#cart_sum", OleDbType.Double,20).Value = temp_total_item_price;
try
{
cmd.ExecuteNonQuery();
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
MessageBox.Show("Data Added To DataBase");
textBoxCurrentCartSumTXT.Clear();
textBoxPricePerOneTXT.Clear();
textBoxQuantityTXT.Clear();
textBoxSumForCurrentItemTXT.Clear();
connect.Close();
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
connect.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
}
To get any rows back from your database storage through a OleDbDataAdapter you need to set its SelectCommand with a command that contains a SELECT statement
da.SelectCommand = new OleDbCommand("SELECT * FROM Receipts", connect);
DataTable dt = new DataTable();
da.Fill(dt);
Actually you are using the same command used to INSERT data as it was the SelectCommand. Obviously it doesn't return records. You should have a duplicate record in your table.
I would change something to your code. If you have more than one record to add to your table (you have a loop there) then there is no sense in extracting data from your db at every loop. I would call the Fill of the table outside the loop. Also a bit performance gain could be obtained defining the OleDbCommand and its parameters just one time before entering the loop. Inside the loop just update the values of the parameters and call ExecuteNonQuery
private void buttonCloseCart_Click(object sender, EventArgs e)
{
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\אורון\documents\visual studio 2012\Projects\CachierPro\CachierPro\CachierProDB.accdb";
connect.Open();
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO Receipts
(ItemName, Quantity, PricePerOne, Total)
VALUES (#temp_item, #temp_item_quantity,
#temp_item_price, #temp_total_item_price)", connect);
cmd.Parameters.Add ("#temp_item", OleDbType.Char, 20);
cmd.Parameters.Add("#temp_item_quantity", OleDbType.Integer, 20);
cmd.Parameters.Add("#temp_item_price", OleDbType.Double, 20);
cmd.Parameters.Add("#cart_sum", OleDbType.Double,20);
for (int i = 0; i < baught_items.Count; i++)
{
string temp_item = baught_items[i].ToString();
int temp_item_quantity = baught_items_quantity[i];
double temp_item_price = baught_items_price[i];
double temp_total_item_price = total_items_price[i];
if (connect.State == ConnectionState.Open)
{
cmd.Parameters["#temp_item"].Value = temp_item;
cmd.Parameters["#temp_item_quantity"].Value = temp_item_quantity;
cmd.Parameters["#temp_item_price"].Value = temp_item_price;
cmd.Parameters["#cart_sum"].Value = temp_total_item_price;
try
{
int addedCount = cmd.ExecuteNonQuery();
if(addedCount == 0)
{
... problems here, record not added for some reasons
}
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
connect.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = new OleDbCommand("SELECT * FROM Receipts", connect);
DataTable dt = new DataTable();
da.Fill(dt);
textBoxCurrentCartSumTXT.Clear();
textBoxPricePerOneTXT.Clear();
textBoxQuantityTXT.Clear();
textBoxSumForCurrentItemTXT.Clear();
connect.Close();
}

How to populate a DataGridView by selecting any table from combo box

I have used the following code for displaying names of my SQL db tables in a combo box.
Now I want that when I click on any of these table names from the combo box, my DGV populates with that table's contents.
private void Form1_Load(object sender, EventArgs e)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select table_name from information_schema.tables";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
comboBox1.DataSource = dtRecord;
comboBox1.DisplayMember = "TABLE_NAME";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Then I used the following code for populating my DGV but it's not working; please help.
private void PopulateGridView()
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strconnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "select * from " + comboBox1.SelectedText;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dtRecord;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue != null)
{
PopulateGridView(comboBox1.SelectedValue.ToString());
}
}
just try this:
update your code in the Form Load with below:
private void Form1_Load(object sender, EventArgs e)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select table_name from information_schema.tables";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
comboBox1.DataSource = dtRecord;
comboBox1.DisplayMember = "table_name";
comboBox1.ValueMember = "table_name";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
so basically you have added one extra line comboBox1.ValueMember = "table_name";
and make your PopulateGridView method like this:
private void PopulateGridView(string tblName)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "select * from " + tblName;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dtRecord;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
it has to work.
Also, I see, you are creating SqlConnection object everywhere, including SqlCommand and SqlDataAdapter.
try to wrap them up in static methods i.e.
- public static SqlConnection OpenConnection()
- public static DataTable ExecuteSelectQuery(string Query)
- public static bool ExecuteModifyQuery(string Query)
try to write as less amount of code as you can.
Try this:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue != null)
{
string strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strconnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "select * from " + comboBox1.SelectedValue;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dtRecord;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

Populating ComboBox with Data

I want to display the items in my database inside the combo box after the radio option is been selected. when i tried this nothing was displayed in the combo box. please kindly help
private void chkDetailsButton_Click(object sender, EventArgs e)
{
if (radioButtonA.Checked)
{
OleDbConnection connect = db.dbConnect();
try
{
connect.Open();
MessageBox.Show("Opened");
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "Select * from Categories";
DataTable dt = new DataTable();
for (int i = 0; i < dt.Rows.Count; i++)
{
cmbDisplay.Items.Add(dt.Rows[i]["SeatNo"]);
}
}
catch (Exception ex)
{
MessageBox.Show("Exception in Database" + ex);
}
finally
{
connect.Close();
}
}
}
Your try block should resemble the following:
try
{
connect.Open();
MessageBox.Show("Opened");
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "Select * from Categories";
DataTable dt = new DataTable();
//Put some data in the datatable!!
using(OleDbDataReader reader = command.ExecuteReader())
{
dt.Load(reader);
}
for (int i = 0; i < dt.Rows.Count; i++)
{
cmbDisplay.Items.Add(dt.Rows[i]["SeatNo"]);
}
}
You need to fill your DataTable with data!
You might also consider the following:
using(OleDbDataReader reader = command.ExecuteReader())
{
while(reader.Read())
{
cmbDisplay.Items.Add(reader.GetValue(reader.GetOrdinal("SeatNo"));
}
}
This way you don't even need to use a DataTable; this is a more efficient approach for large sets of data.
As an aside, you may wish to consider using Using:
using(OleDbConnection connect = db.dbConnect())
{
try
{
connect.Open();
//MessageBox.Show("Opened");
using(OleDbCommand command = new OleDbCommand())
{
command.Connection = connect;
command.CommandText = "SELECT * FROM Categories";
using(IDataReader reader = command.ExecuteReader())
{
while(reader.Read())
{
cmbDisplay.Items.Add(reader.GetValue(reader.GetOrdinal("SeatNo"));
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("An erorr occured:" + ex);
}
}
This will ensure your connection, command and reader objects are disposed. This is not appropriate if you intend to hold onto an instance of your connection however as it will be closed AND disposed as soon as your code leaves the using statement.
There is missing filling DataTable dt with datas, which are returned by your sql command.
try with this code - in your sample you don't bind your table with data, you create new instance of table.
$ private void chkDetailsButton_Click(object sender, EventArgs e)
{
if (radioButtonA.Checked)
{
OleDbConnection connect = db.dbConnect();
try
{
connect.Open();
MessageBox.Show("Opened");
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "Select * from Categories";
OleDbDataReader myReader = command.ExecuteReader();
while (myReader.Read())
{
cmbDisplay.Items.Add(myReader["SeatNo"]);
}
}
catch (Exception ex)
{
MessageBox.Show("Exception in Database" + ex);
}
finally
{
connect.Close();
}
}
}
I can't believe this. :D
When are you exactly filling the DataTable with data from DB?
There is nothing in between
DataTable dt = new DataTable();
and
for (int i = 0; i < dt.Rows.Count; i++)
you can fill combobox with Datatable :
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("select * from Books",con);
DataTable dt = new DataTable();
da.Fill(dt);
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
comboBox1.DataSource = dt;
You are not filling data in Dataset before attaching try this
if(radio.checked)
{
try
{
connect.Open();
MessageBox.Show("Opened");
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "Select * from Categories";
OleDbDataAdapter db = new OleDbDataAdapter();
DataSet ds = new DataSet();
db.SelectCommand = command;
db.Fill(ds);
for(int i=0;i<ds.Tables[0].Rows.Count;i++)
{
cmbDisplay.Items.Add(ds.Tables[0].Rows[i][0].ToString());
}
cmDisplay.DataBind();
}
catch (Exception ex)
{
MessageBox.Show("Exception in Database" + ex);
}
finally
{
connect.Close();
}
}

Categories