I have a 'Create new Order' Form where I create an order which once created in now on the DB Table displayed in a datagridView.
However I am struggling to get the datagridView to auto update with the new data in it.
This is the form:
This is the table where the new order should be displaying. However only displays when i switch tables and not when the New order is created successfully.
I have tried the dataGridView.Refresh() and a bunch of other researched solutions but non seem to work.
This is my Code.
MySqlConnection conn = new MySqlConnection();
conn.Close();
var x = inputOrderTitle.Text;
Random rnd = new Random();
try
{
MySqlConnection mysqlConnection = new MySqlConnection();
connect.OpenSuccessfulDBConnection(mysqlConnection);
String query = "INSERT INTO tb_orders VALUES (#order_id, #title, #description, #scheduled_date, #deadline_date, #word_count, #editor_url, #status, #is_complete, #is_invoiced, #is_closed, #type, #ClientID, #InvoiceID, is_inprogress, #client_name, #order_cost)";
MySqlCommand cmd = new MySqlCommand(query, mysqlConnection);
cmd.Parameters.AddWithValue("#order_id", "BLG0556");
cmd.Parameters.AddWithValue("#title", "abc");
cmd.Parameters.AddWithValue("#description", "abc");
cmd.Parameters.AddWithValue("#scheduled_date", dateTimeSchedDate.Value.Date);
cmd.Parameters.AddWithValue("#deadline_date", dateTimeSubDate.Value.Date);
cmd.Parameters.AddWithValue("#word_count", 123);
cmd.Parameters.AddWithValue("#editor_url", "abc");
cmd.Parameters.AddWithValue("#status", "abc");
cmd.Parameters.AddWithValue("#is_complete", 0);
cmd.Parameters.AddWithValue("#is_invoiced", 0);
cmd.Parameters.AddWithValue("#is_closed", 0);
cmd.Parameters.AddWithValue("#type", comboBoxOrderType.Text);
cmd.Parameters.AddWithValue("#ClientID", 123);
cmd.Parameters.AddWithValue("#InvoiceID", 432);
cmd.Parameters.AddWithValue("#is_inprogress", 1);
cmd.Parameters.AddWithValue("#client_name", "abc");
cmd.Parameters.AddWithValue("#order_cost", 30.00);
int result = cmd.ExecuteNonQuery();
Application.OpenForms
.OfType<Form>()
.Where(form => String.Equals(form.Name, "NewOrder"))
.ToList()
.ForEach(form => form.Close());
MessageBox.Show("Order created successfully.");
orders.dataGridViewOrderList.Rows.Clear();
connect.GetOrderList(orders.dataGridViewOrderList);
}
Use the 'DataSource' property to bind the grid to the bunch of fetched data
SqlConnection mysqlConnection = new SqlConnection("your connection string");
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("Select * from tb_orders(nolock)", mysqlConnection);
if (mysqlConnection.State == ConnectionState.Closed)
mysqlConnection.Open();
da.SelectCommand.ExecuteNonQuery();
da.Fill(dt);
dataGridViewOrderList.DataSource = dt;
Related
I am trying to make a feedback form where I want to show the name which is inserted n number of times.
My DataBase has for example 9 duplicate names as feedback was input for that same person 9 times and I want to display it on the result that common name.
Please help me out to complete the code/solution or Correct the code and get the result.
SQL QUERY IS RUNNING PROPERLY IT IS SELECTING THE SINGLE DATA FROM DATABASE BUT HOW TO SHOW THIS ON WEBPAGE
public void cal_F2name()
{
string oracledb = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP****))(****))(CONNECT_DATA =(SERVER = DEDICATED)(SID = ORCL));";
OracleConnection conn = new OracleConnection(oracledb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
OracleDataAdapter da1 = new OracleDataAdapter();
DataTable dt1 = new DataTable();
DataSet ds1 = new DataSet();
cmd.CommandText = "SELECT DISTINCT (F2NAME) FROM CMDC_FEEDBACK WHERE PRG_NAME ='" + cb_prg_name.SelectedValue + "'";
da1.SelectCommand = cmd;
da1.Fill(ds1);
name = Convert.ToString(ds1.Tables[0].Rows[0][0].ToString());
Label58.Text = String.Format("{0:0.00}",name);
conn.Close();
}
try using below code, i have made some change in sql query to get only single record as result.
public void cal_F2name()
{
string oracledb = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP****))(****))(CONNECT_DATA =(SERVER = DEDICATED)(SID = ORCL));";
OracleConnection conn = new OracleConnection(oracledb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
OracleDataAdapter da1 = new OracleDataAdapter();
DataTable dt1 = new DataTable();
DataSet ds1 = new DataSet();
cmd.CommandText = "SELECT max(DISTINCT (F2NAME)) FROM CMDC_FEEDBACK WHERE PRG_NAME ='" + cb_prg_name.SelectedValue + "' AND F2NAME<>'' AND F2NAME IS NOT NULL" ;
da1.SelectCommand = cmd;
da1.Fill(ds1);
name = Convert.ToString(ds1.Tables[0].Rows[0][0].ToString());
Label58.Text = String.Format("{0:0.00}",name);
conn.Close();
}
i have not check but it will work, if you result binding to lable is correct.
I am trying to update my data in a SQL Server database through C#. I am getting updated. But the problem is the data is updated twice.
For example I have 10 (int) in my balance and if I add another 10, it turns to 30.
Any help would be appreciated.
Here is my code:
protected void LoginClick(object sender, EventArgs e)
{
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
con.Close();
}
I would like to rectify few mistakes in your code,
DataTable is not needed to execute the update query, ExecuteNonQuery will do the job
The adapter.Fill and ExecuteNonQuery do the same job here and that's why your updates happening twice
Make use of parameterization while dealing with user inputs to avoid exceptions
For parsing integers use int.TryParse instead for Convert.ToInt32
I think the following code would help you to do the same function in a smarter way:
int currentBalance = 0;
if(int.TryParse(txtAdd.Text, out currentBalance))
{
string querSql = "Update [Order] set Balance = Balance + #balance," +
" Card = #card where email = #email"
using (SqlConnection dbConn = new SqlConnection("connectionString here"))
{
dbConn.Open();
using (SqlCommand sqlCommand = new SqlCommand(querySql, dbConn))
{
sqlCommand.Parameters.Add("#balance", SqlDbType.int).value = currentBalance;
sqlCommand.Parameters.Add("#card", SqlDbType.VarChar).value = card.Text;
sqlCommand.Parameters.Add("#email", SqlDbType.VarChar).value = email;
sqlCommand.ExecuteNonQuery();
}
}
}
Please note: YOu are parsing the balance as an integer value, so I assume the column Balance is an integer field in the database, if not make use of corresponding datatype for the parameter #balance also update the parsing technique
As per the documentation:
SqlDataAdapter(SqlCommand)
Initializes a new instance of the SqlDataAdapter class with the specified SqlCommand as the SelectCommand property.
What is going wrong in your code?
Actually you are passing SqlDataAdapter your update query as the Select command. So now when you will use this instance of SqlDataAdapter to Fill your datatable then actually you are executing your Update command. Look at the following code along with comments to see what is going wrong:
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
SqlDataAdapter sda = new SqlDataAdapter(cmd);//The Select command for SqlDataAdapter
//is actually now the update command specified by cmd instnace of SqlCommand
DataTable dt = new DataTable();
sda.Fill(dt);//here SqlDataAdapter will execute it's Select command which is actually set
//to an update statement so your record will be updated
int i = cmd.ExecuteNonQuery();//and here again the update command is being executed now
//directly using the SqlCommand cmd instance and thus your record gets updated twice
con.Close();
Fixed Code:
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
//Create a new SqlComamnd
SqlCommand selectCommand = new SqlCommand("Select * from [Order]");
//Put the newly created instance as SelectCommand for your SqlDataAdapter
SqlDataAdapter sda = new SqlDataAdapter(selectCommand);
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
con.Close();
Hope this help and do have a look at the documentation for better understanding of the SqlDataAdapter and DataTable. Thanks.
This is my code:
SqlConnection connection = new SqlConnection(MyConnectionString2);
SqlCommand cmd2;
connection.Open();
try
{
cmd2 = connection.CreateCommand();
cmd2.CommandText = ("INSERT INTO tbl_EmailAdress (Email) VALUES (#EmailAddress);");
cmd2.Parameters.Add("#EmailAddress", SqlDbType.NVarChar);
cmd2.Parameters["#EmailAddress"].Value = TxbAddEmailUser.Text;
SqlDataAdapter adap = new SqlDataAdapter(cmd2);
DataSet ds = new DataSet();
BindingSource bs = new BindingSource();
bs.DataSource = ds.Tables[0];
dataGridView1.DataSource = bs;
}
catch (Exception)
{
throw;
}
TxbAddEmailUser.Clear();
The problem is that my program gives me the error:
System.IndexOutOfRangeException: cannot find tabel 0;
this is my database:
table: tbl_EmailAdress
column: id, int, NOT NULL
column: Email, char(10), NULL
The insert query works, what am I doing wrong?
"Cannot find table 0" indicates that DataSet has empty tables at the first index (0), so that you can't assign data source from it.
The main problem is you're using INSERT command here:
cmd2.CommandText = ("INSERT INTO tbl_EmailAdress (Email) VALUES (#EmailAddress);");
INSERT command is not intended to return any results for SqlDataAdapter, you need to use ExecuteNonQuery:
cmd2 = connection.CreateCommand();
cmd2.CommandText = ("INSERT INTO tbl_EmailAdress (Email) VALUES (#EmailAddress)");
cmd2.Parameters.Add("#EmailAddress", SqlDbType.NVarChar);
cmd2.Parameters["#EmailAddress"].Value = TxbAddEmailUser.Text;
cmd2.ExecuteNonQuery();
Note that ExecuteNonQuery only returns affected rows (i.e. 1 row), and you can't assign dataGridView1.DataSource to a single integer value.
If you want to use SqlDataAdapter, you need to use SELECT statement like this example:
cmd2 = connection.CreateCommand();
cmd2.CommandText = ("SELECT * FROM tbl_EmailAdress WHERE Email = #EmailAddress");
cmd2.Parameters.Add("#EmailAddress", SqlDbType.NVarChar);
cmd2.Parameters["#EmailAddress"].Value = TxbAddEmailUser.Text;
SqlDataAdapter adap = new SqlDataAdapter(cmd2);
DataSet ds = new DataSet();
adap.Fill(ds); // fill the data table from adapter
BindingSource bs = new BindingSource();
bs.DataSource = ds.Tables[0]; // this time the first table is not null or empty
dataGridView1.DataSource = bs;
Similar issue:
Cannot find table 0 error in C#
No need of doing this ,
SqlDataAdapter adap = new SqlDataAdapter(cmd2);
DataSet ds = new DataSet();
BindingSource bs = new BindingSource();
bs.DataSource = ds.Tables[0];
dataGridView1.DataSource = bs;
just use
cmd2.ExecuteNonQuery();
//instantiating connection
dbConn = new SqlConnection("Data Source = local host; initial catalog=Project; Integrated Security = SSPI ");
ds = new DataSet();
//select everything from the table
dbCommand = new SqlCommand("SELECT * FROM Shops;", dbConn);
dbAdapter = new SqlDataAdapter(dbCommand);
//filling the datagrid
dbAdapter.Fill(ds, "All Shops");
dataGridView1.DataSource = ds.Tables["All Shops"];
To show data into datagrid you need to assign datasource and then use DataBind() to bind the data.
dataGridView1.DataSource = ds.Tables["All Shops"];
dataGridView1.DataBind(); // use this after assigning the datasource
private void GetResults()
{
//Establishing the MySQL Connection
MySqlConnection conn = new MySqlConnection("Database=potentiality_live;Data Source=eu;User Id=ptly;Password=phat40");
string query;
MySqlCommand SqlCommand;
MySqlDataReader reader;
MySqlDataAdapter adapter = new MySqlDataAdapter();
//Open the connection to db
conn.Open();
//Generating the query to fetch the contact details
query = "SELECT id,date_time,link FROM'sdfsdfsdf'";
SqlCommand = new MySqlCommand(query, conn);
adapter.SelectCommand = new MySqlCommand(query, conn);
//execute the query
reader = SqlCommand.ExecuteReader();
//Assign the results
GridView1.DataSource = reader;
//Bind the data
GridView1.DataBind();
}
Reference:
http://www.codeproject.com/Questions/453091/how-to-get-data-from-sql-database-to-gridview-by-c
My scenario is to populate combobox from the database, display customer name, and hold a value of the id using identity increment.
When this code is run, I receive an error Procedure or function 'spSelectCustomerById' expects parameter '#id', which was not supplied.
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
//SelectCustomerById(int x);
comboBoxEx1.Items.Clear();
SqlCommand comm = new SqlCommand("spSelectCustomerByID", conn);
//comm.Parameters.Add(new SqlParameter("cust_name", cust_name));
//comm.CommandText = "spSelectCustomerByID";
comm.Parameters.Add(new SqlParameter("cust_id", SqlDbType.Int));
comm.CommandType = CommandType.StoredProcedure;
comm.ExecuteNonQuery();
SqlDataAdapter sdap = new SqlDataAdapter(comm);
DataSet dset = new DataSet();
sdap.Fill(dset, "cust_registrations");
if (dset.Tables["cust_registrations"].Rows.Count > 0)
{
comboBoxEx1.Items.Add("cust_registrations").ToString();
}
comboBoxEx1.DataSource = dset;
comboBoxEx1.DisplayMember = "cust_name";
How can I populate a combobox from a database?
For web combobox us comboBoxEx1.DataValueField = "cust_id";
for WPF you use comboBoxEx1.SelectedValuePath = "cust_id";
in win forms use comboBox1.ValueMember = "cust_id";
conn.Open();
//SelectCustomerById(int x);
comboBoxEx1.Items.Clear();
SqlCommand comm = new SqlCommand("spSelectCustomerByID", conn);
//comm.Parameters.Add(new SqlParameter("cust_name", cust_name));
//comm.CommandText = "spSelectCustomerByID";
comm.Parameters.Add(new SqlParameter("#id", SqlDbType.Int));
comm.CommandType = CommandType.StoredProcedure;
comm.ExecuteNonQuery();
SqlDataAdapter sdap = new SqlDataAdapter(comm);
DataSet dset = new DataSet();
sdap.Fill(dset, "cust_registrations");
comboBoxEx1.DataSource = dset;
comboBoxEx1.DisplayMember = "cust_name";
// Add the following line
// You do not need to add items into the combobox.
comboBoxEx1.ValueMember = "cust_id";
comboBoxEx1.DataBind();