winforms C# using sql server 2008 - c#

private void fillcode()
{
try
{
SqlConnection con = new SqlConnection("Data Source=ANISH;Initial Catalog=HM;Integrated Security=True");
con.Open();
string s = "select max(CustomerId) as Id from CustomerDetails";
SqlCommand cmd = new SqlCommand(s, con);
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
int i = Convert.ToInt16(dr["Id"].ToString());
sid.Text = (i + 1).ToString();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am using this code, but there is a problem if there is no data in my table it will not accept.
So I want to use if no data is present it should take CustomerId as 1

It will be NULL of there are no rows so you can:
"select isnull(max(CustomerId), 1) as Id from CustomerDetails"
You should also look at ExecuteScalar which is designed for a singe result.

Try like this
private void fillcode()
{
try
{
SqlConnection con = new SqlConnection("Data Source=ANISH;Initial Catalog=HM;Integrated Security=True");
con.Open();
string s = "select max(CustomerId) as Id from CustomerDetails";
SqlCommand cmd = new SqlCommand(s, con);
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
int i = Convert.ToInt16(dr["Id"].ToString());
sid.Text = (i + 1).ToString();
}
else
{
sid.Text = "1"
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Related

I have a listview with items which I want to insert into a SQL Server database

I want to save content of a listview into a SQL Server database.
I've tried the commented code but get an error
Must declare scalar variable #Description
Code:
private void btnFinish_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
try
{
foreach (ListViewItem item in lvregion.Items)
{
SqlConnection conn;
SqlCommand comm;
string connectionString = ConfigurationSettings.AppSettings["conn"];
conn = new SqlConnection(connectionString);
comm = new SqlCommand(
"INSERT INTO Region (RegionDescription, Fname, Lname) " +
"VALUES (#RegionDescription, #Fname, #Lname)", conn);
//cmd.Parameters.AddWithValue("RegionDescription", item.Text.Trim());
//cmd.Parameters.AddWithValue("fname", item.SubItems[1].Text.Trim());
//cmd.Parameters.AddWithValue("lname", item.SubItems[2].Text.Trim());
cmd.Parameters.Add("RegionDescription", SqlDbType.VarChar,40);
cmd.Parameters.AddWithValue("RegionDescription", item.Text.Trim());
cmd.Parameters.Add("Fname", SqlDbType.VarChar,40);
cmd.Parameters.AddWithValue("Fname", item.SubItems[1].Text.Trim());
cmd.Parameters.Add("Lname", SqlDbType.VarChar,40);
cmd.Parameters.AddWithValue("Lname", item.SubItems[2].Text.Trim());
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
conn.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Welcome to Stackoverflow,
First up, I wouldn't recommend creating a new connection within your foreach to add items to your table.
Here's what I'd recommend using instead:
try
{
string connectionString = ConfigurationSettings.AppSettings["conn"];
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd;
conn.Open();
string cmdString = #"INSERT INTO Region (RegionDescription, Fname, Lname)
VALUES (#RegionDescription, #Fname, #Lname)";
foreach (ListViewItem item in lvregion.Items)
{
cmd = new SqlCommand(cmdString, conn);
cmd.Parameters.Add("#RegionDescription", SqlDbType.VarChar, 40).Value = item.Text.Trim();
cmd.Parameters.Add("#Fname", SqlDbType.VarChar, 40).Value = item.SubItems[1].Text.Trim();
cmd.Parameters.Add("#Lname", SqlDbType.VarChar, 40).Value = item.SubItems[2].Text.Trim();
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
(Or at least this should have you on the right path.)

quiz with choices using datareader. clicking button to change from number 1 to 4

click a button to change the question in my Form and choices.. but this code only shows the last data of my table when i click it
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=JOSHMAV-PC\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
SqlCommand command = new SqlCommand("SELECT * "+
"FROM question", conn);
try
{
conn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//MessageBox.Show(reader["C1"].ToString());
ques.Text = reader["ques"].ToString();
radioButton1.Text = reader["C1"].ToString();
radioButton2.Text = reader["C2"].ToString();
radioButton3.Text = reader["C3"].ToString();
radioButton4.Text = reader["C4"].ToString();
}
reader.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
im only starting in sql server
you should add some int type of data and you should check it from you sql statement then
you can get your willing data from database it something like this
don't forget to increment it in somewhere of you program and keep in mind of boundary of it
SqlConnection conn = new SqlConnection("Data Source=JOSHMAV-PC\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
SqlCommand command = new SqlCommand("SELECT * "+
"FROM question where id ="+one, conn);
public class Form1
{
private SqlConnection conn;
private SqlCommand command;
private SqlDataReader reader;
public Form1()
{
conn = new SqlConnection("Data Source=JOSHMAV-PC\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
command = new SqlCommand("SELECT * "+ "FROM question", conn);
try
{
conn.Open();
reader = command.ExecuteReader();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (reader.Read())
{
//MessageBox.Show(reader["C1"].ToString());
ques.Text = reader["ques"].ToString();
radioButton1.Text = reader["C1"].ToString();
radioButton2.Text = reader["C2"].ToString();
radioButton3.Text = reader["C3"].ToString();
radioButton4.Text = reader["C4"].ToString();
}
else reader.Close();
}
}

Retrieve Database values and show them on form using SQLDataReader

I am trying to retrieve data from a Database and show them on a form; but my code isn't working... I've got no errors, and logically it seems to work (to me) so I cannot figure out where I have gone wrong. That's where I need your help!
private void tableListBox_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE Default_Name = '" + tableListBox.SelectedValue + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader Reader;
try
{
con.Open();
Reader = cmd.ExecuteReader();
while (Reader.Read())
{
textBox1.Text = Reader.GetValue(2).ToString();
comboBox1.Text = Reader.GetValue(3).ToString();
comboBox3.Text = Reader.GetValue(4).ToString();
textBox2.Text = Reader.GetValue(6).ToString();
comboBox2.Text = Reader.GetValue(7).ToString();
comboBox4.Text = Reader.GetValue(8).ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
The 'tableListBox' is populated with all the values in column 'Default_Name'. I want it so that when the 'Default_Name' is selected from the list box it shows the values, in textboxes and comboboxes, that correspond with that row in the Database.
Any and all help would be appreciated. Thanks.
I'm going to start by changing your design a bit and suggest that perhaps you look at using a datatable and then just retrieving the rows from the datatable.
private void tableListBox_SelectedIndexChanged(object sender, EventArgs e)
{
private DataTable dataTable;
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE Default_Name = '" + tableListBox.SelectedValue + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dataTable);
foreach(DataRow row in dataTable.Rows)
{
textBox1.Text = row[2].ToString();
comboBox1.Text = row[3].ToString();
comboBox3.Text = row[4].ToString();
textBox2.Text = row[6].ToString();
comboBox2.Text = row[7].ToString();
comboBox4.Text = row[8].ToString();
}
da.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
I generally find that DataTables are more reliable than looping through the actual reader. Ofcourse this assumes that there is data being returned. Also try changing your select statement to this
string Query = "SELECT * FROM [Table]"
If that works, then the problem could be
There is no default name of the specified value or
tableListBox.SelectedValue is not returning any value, in which case, have a look at your listbox selected value
Thanks to Takarii for helping. I figured out who to make it work.
private void tableListBox_SelectedValueChanged(object sender, EventArgs e)
{
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE ID = '" + tableListBox.SelectedIndex.ToString() + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader Reader;
try
{
con.Open();
Reader = cmd.ExecuteReader();
while (Reader.Read())
{
textBox1.Text = Reader.GetValue(2).ToString();
comboBox1.Text = Reader.GetValue(3).ToString();
comboBox3.Text = Reader.GetValue(4).ToString();
textBox2.Text = Reader.GetValue(6).ToString();
comboBox2.Text = Reader.GetValue(7).ToString();
comboBox4.Text = Reader.GetValue(8).ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
First I changed the void to 'SelectedValueChanged' and then I changed the 'WHERE' in the connection Query to the Row Index associated with the selected Value.
Thanks for everyone's help!

SQL visual studio command

i am trying to update a mysql database through visual studio
String str = "server=localhost;database=population;username=root;password=hello;Convert Zero Datetime=true;";
MySqlConnection con = new MySqlConnection(str);
string col1 = col.Text;
string newval1=newval.Text;
string val1=val.Text;
try
{
con.Open();
string cmdstr="update npanxx set \""+col1+"\" = \""+newval1+"\" where NPA_NXX=\""+val1+"\"";
MySqlCommand cmd = new MySqlCommand(cmdstr, con);
cmd.ExecuteNonQuery();
con.Close();
}
catch(Exception err)
{
MessageBox.Show(err.ToString());
}
when I run this and click the button it says I have a syntax error but I have not be able to find it. Can anyone point it out to me
You don't need quotes around the column col1:
String str = "server=localhost;database=population;username=root;password=hello;Convert Zero Datetime=true;";
MySqlConnection con = new MySqlConnection(str);
string col1 = col.Text;
string newval1=newval.Text;
string val1=val.Text;
try
{
con.Open();
string cmdstr="update npanxx set "+col1+" = \""+newval1+"\" where NPA_NXX=\""+val1+"\"";
MySqlCommand cmd = new MySqlCommand(cmdstr, con);
cmd.ExecuteNonQuery();
con.Close();
}
catch(Exception err)
{
MessageBox.Show(err.ToString());
}
I would do it this way:
String str = "server=localhost;database=population;username=root;password=hello;Convert Zero Datetime=true;";
MySqlConnection con = new MySqlConnection(str);
string col1 = col.Text;
string newval1=newval.Text;
string val1=val.Text;
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand("Update npanxx set '"+ col1 +"'='" + newval1 + "' WHERE NPA_NXX= '" + val1 + "'", con);
MySqlCommand cmd = new MySqlCommand(cmdstr, con);
cmd.ExecuteNonQuery();
con.Close();
}
catch(Exception err)
{
MessageBox.Show(err.ToString());
}

The variable name '#KorisnickoIme' has already been declared. Variable names must be unique within a query batch or stored procedure

I try to sort the data from GridView you receive error(Is Enable Sorting).Variable names must be unique within a query batch or stored procedure.
2.Here and adapters
{
istorijaKupovinaDataSource.SelectCommand = #"
SELECT k.Datum, p.Naziv AS Proizvodjac, l.Naziv AS Lek, k.Kolicina, k.Cena, ni.Naziv AS NacinIsporuke
FROM Kupovina k
INNER JOIN Lek l ON k.LekId = l.Id
INNER JOIN NacinIsporuke ni ON k.NacinIsporukeID = ni.Id
INNER JOIN Proizvodjac p ON l.ProizvodjacId = p.Id
INNER JOIN Kupac u ON k.KupacId = u.Id
WHERE u.KorisnickoIme = #KorisnickoIme
ORDER BY k.Datum";
istorijaKupovinaDataSource.SelectParameters.Add("KorisnickoIme", DbType.String, User.Identity.Name);
}
public static void Kupi(long lekID, int kolicina, decimal cena, long nacinIsporukeID, string korisnickoIme)
{
SqlConnection con = new SqlConnection();
try
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["OnlineApotekaConnectionString"].ConnectionString;
con.Open();
string updateLager = #"
UPDATE Lager
SET Kolicina=Kolicina-#Kolicina
WHERE LekID=#LekID";
SqlCommand cmd = new SqlCommand(updateLager, con);
cmd.Parameters.AddWithValue("#LekID", lekID);
cmd.Parameters.AddWithValue("#Kolicina", kolicina);
cmd.ExecuteNonQuery();
string insertIntoKupovina=#"
INSERT INTO Kupovina (KupacID, LekID, Datum, Kolicina, Cena, NacinIsporukeID)
VALUES (#KupacID, #LekID, #Datum, #Kolicina, #Cena, #NacinIsporukeID)";
cmd = new SqlCommand(insertIntoKupovina, con);
cmd.Parameters.AddWithValue("#KupacID", KupacAdapter.GetID(korisnickoIme));
cmd.Parameters.AddWithValue("#LekID", lekID);
cmd.Parameters.AddWithValue("#Datum", DateTime.Now.Date);
cmd.Parameters.AddWithValue("#Kolicina", kolicina);
cmd.Parameters.AddWithValue("#Cena", cena);
cmd.Parameters.AddWithValue("#NacinIsporukeID", nacinIsporukeID);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}
}
{
SqlConnection con = new SqlConnection();
try
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["OnlineApotekaConnectionString"].ConnectionString;
con.Open();
string selectQuery = #"
SELECT ID
FROM Kupac
WHERE KorisnickoIme = #KorisnickoIme";
SqlCommand cmd = new SqlCommand(selectQuery, con);
cmd.Parameters.AddWithValue("#KorisnickoIme", korisnickoIme);
return Convert.ToInt64(cmd.ExecuteScalar());
}
catch (Exception err)
{
throw err;
}
finally
{
con.Close();
}
}
public List<Kupac> SelectAll()
{
List<Kupac> list = new List<Kupac>();
SqlConnection con = new SqlConnection();
try
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["OnlineAotekaConnectionString"].ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
string selectQuery = "SELECT * FROM Kupac";
cmd.CommandText = selectQuery;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
list.Add(new Kupac(reader["Jmbg"].ToString(), reader["Ime"].ToString(), reader["Prezime"].ToString(), reader["Telefon"].ToString(), reader["Adresa"].ToString(), reader["Email"].ToString(), reader["KorisnickoIme"].ToString()));
}
reader.Close();
return list;
}
catch (Exception err)
{
throw err;
}
finally
{
con.Close();
}
}
}
I think you should use
istorijaKupovinaDataSource.SelectParameters.Clear();
istorijaKupovinaDataSource.SelectParameters.Add("KorisnickoIme", DbType.String, User.Identity.Name);
instead of
istorijaKupovinaDataSource.SelectParameters.Add("KorisnickoIme", DbType.String, User.Identity.Name);

Categories

Resources