I just want to clarify, can i refresh datagridview after insert or update or delete without selecting new sql query again ?
i have googled it, and still have no idea to do it.
here's my code
private void button4_Click(object sender, EventArgs e)
{
employee();
}
public void employee()
{
DataTable dtclubroom = new DataTable();
SqlCommand command = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter(command.CommandText, myConnection);
try
{
myConnection.Open();
dtclubroom.Clear();
command.Connection = myConnection;
command.CommandText = "Select * from employee ";
adapter.SelectCommand = command;
adapter.Fill(dtclubroom);
dataGridView2.DataSource = dtclubroom;
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}
finally
{
myConnection.Close();
}
}
private void button5_Click(object sender, EventArgs e)
{
SqlCommand command2 = new SqlCommand();
try
{
myConnection.Open();
command2.CommandText = "insert into employee (name,id) values (#name,#id)";
command2.Connection = myConnection;
command2.Parameters.AddWithValue("#name","Leon");
command2.Parameters.AddWithValue("#id", "002");
command2.ExecuteNonQuery();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
finally
{
myConnection.Close();
}
employee() //<- refresh datagridview
}
Button 4 is to load data, and button 5 inserting data also load data. is there a way refresh datagridview without calling employee() method again ?
You can do it in couple of ways.
Add the newly inserted record to your datatable (you need to use a global datatable variable for this) and refresh your Grid View using this datatable.
You can add the newly inserted record directly to the Grid View
You can follow these techniques also for DELETE and UPDATE
Here is the implementation of idea #1 for your existing code :
DataTable dtclubroom = new DataTable();
private void button4_Click(object sender, EventArgs e)
{
employee();
}
public void employee()
{
SqlCommand command = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter(command.CommandText, myConnection);
try
{
myConnection.Open();
dtclubroom.Clear();
command.Connection = myConnection;
command.CommandText = "Select * from employee ";
adapter.SelectCommand = command;
adapter.Fill(dtclubroom);
dataGridView2.DataSource = dtclubroom;
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}
finally
{
myConnection.Close();
}
}
private void button5_Click(object sender, EventArgs e)
{
SqlCommand command2 = new SqlCommand();
try
{
myConnection.Open();
command2.CommandText = "insert into employee (name,id) values (#name,#id)";
command2.Connection = myConnection;
command2.Parameters.AddWithValue("#name","Leon");
command2.Parameters.AddWithValue("#id", "002");
command2.ExecuteNonQuery();
DataRow dr = dtclubroom.NewRow();
dr["name"] = "Leon";
dr["id"] = "002";
dtclubroom.Rows.Add(dr);
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
finally
{
myConnection.Close();
}
dataGridView2.DataSource = dtclubroom; //<- refresh datagridview
}
Look that the datatable declaration is moved up and you need to place it in top of your class :
DataTable dtclubroom = new DataTable();
Nothing else need to be global.
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;
}
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 ! ");
}
}
}
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);
}
}
}
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();
}
}