I Inserted Data to ComboBox using Folloowing Code in FormLoad Block
try
{
using (SqlConnection con = new SqlConnection(conString))
{
SelectCategoryComboBox.Items.Clear();
string query = "SELECT CategoryName FROM CategoryTable";
con.Open();
SqlDataReader sdr = new SqlCommand(query, con).ExecuteReader();
while (sdr.Read())
{
SelectCategoryComboBox.Items.Add(sdr.GetValue(0).ToString());
}
}
}
catch
{
StatusLabel.Text = "An error occured while loading Data";
}
finally
{
SelectCategoryComboBox.SelectedItem = null;
SelectCategoryComboBox.SelectedText = "Choose Category";
}
it does the Job. in the Form You can Create a Category and Delete By Selecting The Name of the category from ComboBox Here is a ScreenShot the Form. I used the following code to Delete and Load the items to ComboBox after Deleting.
try
{
String conString = ConfigurationManager.ConnectionStrings["mfcdb"].ConnectionString;
String query = "DELETE FROM CategoryTable WHERE CategoryName='" + SelectCategoryComboBox.SelectedItem.ToString() + "'";
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
}
StatusLabel.Text = "You have successfully deleted " + SelectCategoryComboBox.SelectedItem.ToString() + " Category";
}
catch
{
StatusLabel.Text = "An Error occured while deleting " + SelectCategoryComboBox.SelectedItem.ToString() + " Category";
}
finally
{
try
{
SelectCategoryComboBox.Items.Clear();
String conString = ConfigurationManager.ConnectionStrings["mfcdb"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
string query = "SELECT CategoryName FROM CategoryTable";
con.Open();
SqlDataReader sdr = new SqlCommand(query, con).ExecuteReader();
while (sdr.Read())
{
SelectCategoryComboBox.Items.Add(sdr.GetValue(0).ToString());
}
}
}
catch
{
StatusLabel.Text = "An error occured while loading Data";
}
finally
{
SelectCategoryComboBox.SelectedItem = null;
SelectCategoryComboBox.SelectedText = "Choose Category";
}
code for Creating new item Given below
if (CategoryNameText.Text == "")
{
StatusLabel.Text = "You have to provide a name to create a category";
}
else
{
String conString = ConfigurationManager.ConnectionStrings["mfcdb"].ConnectionString;
String query = "INSERT INTO CategoryTable(CategoryName) VALUES('" + CategoryNameText.Text + "')";
try
{
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
}
StatusLabel.Text = "You have successfully created " + CategoryNameText.Text + " Category";
try
{
using (SqlConnection scon = new SqlConnection(conString))
{
string locQuery = "SELECT CategoryName,Categoryid FROM CategoryTable";
SqlDataAdapter da = new SqlDataAdapter(locQuery, scon);
scon.Open();
DataSet ds = new DataSet();
da.Fill(ds, "CategoryTable");
SelectCategoryComboBox.ValueMember = "Categoryid";
SelectCategoryComboBox.DisplayMember = "CategoryName";
SelectCategoryComboBox.DataSource = ds.Tables["CategoryTable"];
}
}
catch
{
Thread.Sleep(3000);
StatusLabel.Text = "An Error Occured while Loading Data!";
}
finally
{
SelectCategoryComboBox.SelectedItem = null;
SelectCategoryComboBox.SelectedText = "Choose Category";
}
CategoryNameText.Focus();
}
catch
{
Thread.Sleep(3000);
StatusLabel.Text = ("An ERROR occured While creating category!");
}
finally
{
CategoryNameText.Text = "Enter Category Name";
}
}
}
This Code Deletes Items Perfectly.But If I delete an Item Which is Already in the ComboBox, it does the Job i.e it deletes and Load the Remaining items to ComboBox.but, if I Created an Item,and Deleted it Before Closing the Form, it deletes the item.But Fails to Load the remaining items.it shows all the items already exist in the ComboBox Before Deleting. Would be a great help if you can help me solve this problem. Here SelectCategoryComboBox is the Name of the ComboBox.
I find the problem occur in the following sentence.
String query = "INSERT INTO CategoryTable(CategoryName) VALUES('" + CategoryNameText.Text + "')";
I have two solutions.
First, Please set the Allow nulls for other field.
Like the following:
Second, you can use the following code to replace the original code.
string query = string.Format("INSERT INTO Student(CategoryName, CategoryId, Age) VALUES('{0}','{1}','{2}')",textBox1.Text,textBox2.Text,textBox3.Text);
I found What went Wrong...
Change Following Code
using (SqlConnection scon = new SqlConnection(conString))
{
string locQuery = "SELECT CategoryName,Categoryid FROM CategoryTable";
SqlDataAdapter da = new SqlDataAdapter(locQuery, scon);
scon.Open();
DataSet ds = new DataSet();
da.Fill(ds, "CategoryTable");
SelectCategoryComboBox.ValueMember = "Categoryid";
SelectCategoryComboBox.DisplayMember = "CategoryName";
SelectCategoryComboBox.DataSource = ds.Tables["CategoryTable"];
}
To
using (SqlConnection con = new SqlConnection(conString))
{
SelectCategoryComboBox.Items.Clear();
string squery = "SELECT CategoryName FROM CategoryTable";
con.Open();
SqlDataReader sdr = new SqlCommand(squery, con).ExecuteReader();
while (sdr.Read())
{
SelectCategoryComboBox.Items.Add(sdr.GetValue(0).ToString());
}
}
it Worked for me.
I am unable to find the problem here but this does not work! Any help will be appreciated.
It is a bool thing BTW.Every time i debug, it logs an error as follows
Invalid attempt to read when no data is present
ICCqueueLabelDropDownList.Items.Clear();
string queryString = "(SELECT [name] FROM [asterisk].[dbo].[sip_friends] where name = '" + phoneNumberDropDownList.SelectedItem + "');";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand selectCmd = new SqlCommand(queryString, conn);
SqlDataReader myReader = null;
bool value = false;
try
{
conn.Open();
myReader = selectCmd.ExecuteReader();
//myReader.Read();
if (myReader["name"].ToString() != "" ) /* ( myReader["name"].ToString() != "" */
{
myReader.Read();
value = true;
}
}
catch (Exception ex)
{
//ErrorLabel.Text = ex.Message;
hiba.Visible = true;
hiba.Text = ex.Message + "\n Check Insert Call User Device ÁLERT!";
}
myReader.Close();
conn.Close();
return (value);
}
#andrew, kindly go through below code and let me know is it working for you or not?
string connectionString = "[YOUR_CONNECTION_STRING]";
ICCqueueLabelDropDownList.Items.Clear();
string queryString = "(SELECT [name] FROM [asterisk].[dbo].[sip_friends] where name = '" + phoneNumberDropDownList.SelectedItem + "');";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand selectCmd = new SqlCommand(queryString, conn);
SqlDataReader myReader = null;
bool value = false;
try
{
conn.Open();
myReader = selectCmd.ExecuteReader();
if (myReader.Read())
{
if (myReader["name"].ToString() != "")
{
value = true;
}
}
}
catch (Exception ex)
{
}
myReader.Close();
conn.Close();
return (value);
}
I have filled the drop down menu with names from the my UserData database. I am currently trying to select an users name to make their user details appear in the textboxes, however when I try to select an option from the dropdown menu, the first option always appears in the textboxes I was wondering if anybody could see a problem in my code?
protected void BtnSelect_Click(object sender, EventArgs e)
{
SqlDataReader reader;
String connString = ConfigurationManager
.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
SqlCommand comm1 = new SqlCommand(
"SELECT FirstName, LastName, Email FROM UserData " +
"WHERE TeacherID = #TeacherID", conn);
comm1.Parameters.Add("#TeacherID", System.Data.SqlDbType.Int);
comm1.Parameters["#TeacherID"].Value = DropDownList1.SelectedItem.Value;
try
{
conn.Open();
reader = comm1.ExecuteReader();
if (reader.Read())
{
txtFirstName.Text = reader["FirstName"].ToString();
txtLastName.Text = reader["LastName"].ToString();
txtEmail.Text = reader["Email"].ToString();
}
reader.Close();
}
catch (Exception ex)
{
dbErrorLabel.Text = ("Error in retrieval"+ ex.StackTrace);
}
finally
{
conn.Close();
}
}
Try altering your code slightly like this and then you will find it easier to debug. Check what value you're getting for the selected value (is it what you expect) and also what the content of the actual exception is that you're getting.
This should help you to work out what's going on.
protected void BtnSelect_Click(object sender, EventArgs e)
{
SqlDataReader reader;
String connString = ConfigurationManager
.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
SqlCommand comm1 = new SqlCommand(
"SELECT FirstName, LastName, Email FROM UserData " +
"WHERE TeacherID = #TeacherID", conn);
var selectedValue = DropDownList1.SelectedItem.Value;
var selected = int.Parse(selectedValue);
comm1.Parameters.Add("#TeacherID", System.Data.SqlDbType.Int);
comm1.Parameters["#TeacherID"].Value = selected;
try
{
conn.Open();
reader = comm1.ExecuteReader();
if (reader.Read())
{
txtFirstName.Text = reader["FirstName"].ToString();
txtLastName.Text = reader["LastName"].ToString();
txtEmail.Text = reader["Email"].ToString();
}
reader.Close();
}
catch(Exception ex)
{
dbErrorLabel.Text = ("Error in retrieval " + ex.StackTrace );
}
finally
{
conn.Close();
}
}
When I am reading data from a sql db and want to add all the items into a list (ie. eonumlist) below. Do I need to specifically assign each field or can I mass assign this data? I'm doing this for a report and want to get the data quickly. Maybe I should use a dataset instead. I have 40+ fields to bring into the report and want to do this quickly. Looking for suggestions.
public static List<EngOrd> GetDistinctEONum()
{
List<EngOrd> eonumlist = new List<EngOrd>();
SqlConnection cnn = SqlDB.GetConnection();
string strsql = "select distinct eonum " +
"from engord " +
"union " +
"select 'zALL' as eonum " +
"order by eonum desc";
SqlCommand cmd = new SqlCommand(strsql, cnn);
try
{
cnn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
EngOrd engord = new EngOrd();
engord.EONum = reader["eonum"].ToString();
engord.Name = reader["name"].ToString();
engord.Address = reader["address"].ToString();
eonumlist.Add(engord);
}
reader.Close();
}
catch (SqlException ex)
{
throw ex;
}
finally
{
cnn.Close();
}
return eonumlist;
}
I do something similar storing data from a db into a combo box.
To do this i use the following code.
public static void FillDropDownList(System.Windows.Forms.ComboBox cboMethodName, String myDSN, String myServer)
{
SqlDataReader myReader;
String ConnectionString = "Server="+myServer+"\\sql2008r2;Database="+myDSN+";Trusted_Connection=True;";
using (SqlConnection cn = new SqlConnection(ConnectionString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("select * from tablename", cn);
using (myReader = cmd.ExecuteReader())
{
while (myReader.Read())
{
cboMethodName.Items.Add(myReader.GetValue(0).ToString());
}
}
}
catch (SqlException e)
{
MessageBox.Show(e.ToString());
return;
}
}
}
This connects to the database and reads each record of the table adding the value in column 0 (Name) to a combo box.
I would think you can do something similar with a list making sure the index values are correct.
Store the data as xml, then deserialize the xml to the list.
I'm having an issue at the moment which I am trying to fix. I just tried to access a database and insert some values with the help of C#
The things I tried (worked)
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES ('abc', 'abc', 'abc', 'abc')";
A new line was inserted and everything worked fine, now I tried to insert a row using variables:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id, #username, #password, #email)";
command.Parameters.AddWithValue("#id","abc")
command.Parameters.AddWithValue("#username","abc")
command.Parameters.AddWithValue("#password","abc")
command.Parameters.AddWithValue("#email","abc")
command.ExecuteNonQuery();
Didn't work, no values were inserted. I tried one more thing
command.Parameters.AddWithValue("#id", SqlDbType.NChar);
command.Parameters["#id"].Value = "abc";
command.Parameters.AddWithValue("#username", SqlDbType.NChar);
command.Parameters["#username"].Value = "abc";
command.Parameters.AddWithValue("#password", SqlDbType.NChar);
command.Parameters["#password"].Value = "abc";
command.Parameters.AddWithValue("#email", SqlDbType.NChar);
command.Parameters["#email"].Value = "abc";
command.ExecuteNonQuery();
May anyone tell me what I am doing wrong?
Kind regards
EDIT:
in one other line I was creating a new SQL-Command
var cmd = new SqlCommand(query, connection);
Still not working and I can't find anything wrong in the code above.
I assume you have a connection to your database and you can not do the insert parameters using c #.
You are not adding the parameters in your query. It should look like:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("#id","abc");
command.Parameters.Add("#username","abc");
command.Parameters.Add("#password","abc");
command.Parameters.Add("#email","abc");
command.ExecuteNonQuery();
Updated:
using(SqlConnection connection = new SqlConnection(_connectionString))
{
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
using(SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("#id", "abc");
command.Parameters.AddWithValue("#username", "abc");
command.Parameters.AddWithValue("#password", "abc");
command.Parameters.AddWithValue("#email", "abc");
connection.Open();
int result = command.ExecuteNonQuery();
// Check Error
if(result < 0)
Console.WriteLine("Error inserting data into Database!");
}
}
Try
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username, #password, #email)";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand(query, connection))
{
//a shorter syntax to adding parameters
command.Parameters.Add("#id", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#username", SqlDbType.NChar).Value = "abc";
//a longer syntax for adding parameters
command.Parameters.Add("#password", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#email", SqlDbType.NChar).Value = "abc";
//make sure you open and close(after executing) the connection
connection.Open();
command.ExecuteNonQuery();
}
The most common mistake (especially when using express) to the "my insert didn't happen" is : looking in the wrong file.
If you are using file-based express (rather than strongly attached), then the file in your project folder (say, c:\dev\myproject\mydb.mbd) is not the file that is used in your program. When you build, that file is copied - for example to c:\dev\myproject\bin\debug\mydb.mbd; your program executes in the context of c:\dev\myproject\bin\debug\, and so it is here that you need to look to see if the edit actually happened. To check for sure: query for the data inside the application (after inserting it).
static SqlConnection myConnection;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myConnection = new SqlConnection("server=localhost;" +
"Trusted_Connection=true;" +
"database=zxc; " +
"connection timeout=30");
try
{
myConnection.Open();
label1.Text = "connect successful";
}
catch (SqlException ex)
{
label1.Text = "connect fail";
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
String st = "INSERT INTO supplier(supplier_id, supplier_name)VALUES(" + textBox1.Text + ", " + textBox2.Text + ")";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("insert successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (#txtitemid,#txtitemname,#txtitemdesc,#txtitemqty)";
try
{
using (SqlCommand command = new SqlCommand(query, con))
{
command.Parameters.AddWithValue("#txtitemid", txtitemid.Text);
command.Parameters.AddWithValue("#txtitemname", txtitemname.Text);
command.Parameters.AddWithValue("#txtitemdesc", txtitemdesc.Text);
command.Parameters.AddWithValue("#txtitemqty", txtitemqty.Text);
con.Open();
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error");
MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
loader();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
public static string textDataSource = "Data Source=localhost;Initial
Catalog=TEST_C;User ID=sa;Password=P#ssw0rd";
public static bool ExtSql(string sql) {
SqlConnection cnn;
SqlCommand cmd;
cnn = new SqlConnection(textDataSource);
cmd = new SqlCommand(sql, cnn);
try {
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
return true;
}
catch (Exception) {
return false;
}
finally {
cmd.Dispose();
cnn = null;
cmd = null;
}
}
I have just wrote a reusable method for that, there is no answer here with reusable method so why not to share...here is the code from my current project:
public static int ParametersCommand(string query,List<SqlParameter> parameters)
{
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{ // for cases where no parameters needed
if (parameters != null)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
connection.Open();
int result = cmd.ExecuteNonQuery();
return result;
}
}
catch (Exception ex)
{
AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
return 0;
throw;
}
finally
{
CloseConnection(ref connection);
}
}
private static void CloseConnection(ref SqlConnection conn)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
class Program
{
static void Main(string[] args)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
connetionString = "Data Source=Server Name;Initial Catalog=DataBaseName;User ID=UserID;Password=Password";
sql = "INSERT INTO LoanRequest(idLoanRequest,RequestDate,Pickupdate,ReturnDate,EventDescription,LocationOfEvent,ApprovalComments,Quantity,Approved,EquipmentAvailable,ModifyRequest,Equipment,Requester)VALUES('5','2016-1-1','2016-2-2','2016-3-3','DescP','Loca1','Appcoment','2','true','true','true','4','5')";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
Console.WriteLine(" Connection Opened ");
command = new SqlCommand(sql, connection);
SqlDataReader dr1 = command.ExecuteReader();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine("Can not open connection ! ");
}
}
}