How do I fill the combobox with tables (not columns in specific table) in database.
I already did something common like "Data Bound", but when I ran/debug the system, nothing appears in combobox.
Here's my code:
private void Form1_Load(object sender, EventArgs e)
{
try
{
SqlConnection connection = new SqlConnection(#"Data Source=USER-PC;Initial Catalog=StudentDB;Integrated Security=True");
string selectQuery = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'";
connection.Open();
SqlCommand command = new SqlCommand(selectQuery, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
comboBox1.Items.Add(reader.GetString("tables"));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Any help from experienced developers out there?
the column name is wrong in your code, READER["tables"], the correct column name is TABLE_NAME, try the code below :
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand com = new SqlCommand("SELECT * FROM INFORMATION_SCHEMA.TABLES", con))
{
using (SqlDataReader reader = com.ExecuteReader())
{
myComboBox.Items.Clear();
while (reader.Read())
{
myComboBox.Items.Add((string) reader["TABLE_NAME"]);
}
}
}
}
Related
I have multiple row data in a single column. I need to save all data in to a MySQL DB. But it's only saving selected rows data only in DataGridView.
Below is my sample code.
private void button1_Click(object sender, EventArgs e)
{
string price = dataGridView1[3, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string Query = "INSERT INTO db1.table1 (price) VALUES ('"+ price +"');";
MySqlConnection myConn = new MySqlConnection(MySQLConn);
MySqlCommand MySQLcmd = new MySqlCommand(Query, myConn);
MySqlDataReader myReader;
try
{
myConn.Open();
myReader = MySQLcmd.ExecuteReader();
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Appreciate any help 🙂
Thank you!
One way is to use Foreach loop to get all rows value one by one in DataGridView and then insert them.
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string constring = "Connection String";
using (MySqlConnection con = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand("INSERT INTO db1.table1 (price) VALUES (#price", con))
{
cmd.Parameters.AddWithValue("#price", row.Cells["ColumnName"].Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
If you want to save all rows from your Gridview then loop through it and pick up the column value to save.
Also if you want to save/update to the database, you should use ExecuteNonQuery. Finally, dispose of the objects you're creating and the reason for using.
using (MySqlConnection myConn = new MySqlConnection(MySQLConn))
{
myConn.Open();
MySqlCommand MySQLcmd = new MySqlCommand(Query, myConn);
MySqlParameter priceParameter = new MySqlParameter("#price");
MySQLcmd.Parameters.Add(priceParameter);
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var price = row.Cells["PRICE_COLUMN_NAME"].Value;
MySQLcmd.Parameters["#price"].Value = price;
MySQLcmd.ExecuteNonQuery();
}
}
Dear mbharanidharan88 and user3501749, Thanks for quick support.
With your sup I fond a new code.
Below is my full working code (for me).
private void button1_Click(object sender, EventArgs e)
{
try
{
string MySQLConn = "datasource=localhost;port=3306;username=root;password=root;";
MySqlConnection myConn = new MySqlConnection(MySQLConn);
myConn.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
string price = dataGridView1.Rows[i].Cells[3].Value.ToString();
string Query = "INSERT INTO db1.table1 (price) VALUES ('"+ price + "');";
MySqlCommand MySQLcmd = new MySqlCommand(Query, myConn);
MySQLcmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
If anything wrong let me know 🙂
Can someone help me out?
I just get as result tb_localidade: System.Data.SqlClient.SqlDataReader
Why? Here is the code:
private void btn_normalizar_Click(object sender, EventArgs e)
{
//connection string - one or other doenst work
//SqlConnection conn = new SqlConnection("DataSource=FRANCISCO_GP;Initial Catalog=Normalizacao;Integrated Security=True;");
SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString);
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader leitor = cmd.ExecuteReader();
tb_localidade.Text = leitor.ToString();
conn.Close();
}
You can do this by calling Read() on your data reader and assigning the results:
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlDataReader leitor = cmd.ExecuteReader();
while (leitor.Read())
{
tb_localidade.Text = leitor["ART_DESIG"].ToString();
}
}
}
}
Another note is that using a using block for your SqlConnection and SqlCommand objects is a good habit to get into.
Note: this is assigning the result to the tb_localidade.Text for every row in the resultset. If you are only intending for this to be one record, you might want to look into .ExecuteScalar() instead (see below).
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
tb_localidade.Text = cmd.ExecuteScalar().ToString();
}
}
}
before execute "executeReader()" then you must read to get results.
Improvement on Siyual's response. You're only looking for a single result, and this explicitly disposes both the connection and the datareader.
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using(SqlCommand cmd = new SqlCommand(sql, conn)) {
using(SqlDataReader leitor = cmd.ExecuteReader())
{
if (leitor.Read())
{
tb_localidade.Text = leitor["ART_DESIG"].ToString();
}
}
}
}
}
you should just this
SqlDataReader leitor = cmd.ExecuteReader();
string res="";
while(leitor.Read())
{
res=leitor.GetValue(0).ToString()///////if in sql it is varchar or nvarshar
}
tb_localidade.Text = res;
actully datareader is a 1d table and we can access to this with GetValue or GetInt32 or ...
I am trying to display some values in textboxes from a database by selecting a site ID from a drop down list. The drop down list is working perfectly and showing the site IDs that are stored in the database. While running this application it shows an error:
Execute Reader requires an open and available Connection. The connection's current state is closed.
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadOption();
}
}
private void LoadOption()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(#"connectionString");
using (con)
{
SqlDataAdapter adpt = new SqlDataAdapter("SELECT Site_ID FROM tbl_Survey1", con);
adpt.Fill(dt);
ddlSiteID.DataSource = dt;
ddlSiteID.DataTextField = "Site_ID";
ddlSiteID.DataValueField = "Site_ID";
ddlSiteID.DataBind();
ddlSiteID.Items.Insert(0, new ListItem("--Select ID--", ""));
}
}
protected void ddlSiteID_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"connectionString");
string selectID = ddlSiteID.SelectedValue;
SqlCommand cmd = new SqlCommand("SELECT Site_Name,Site_Address FROM tbl_Survey1 where Site_ID=#Site_ID", con);
cmd.Parameters.AddWithValue("#Site_ID", selectID);
cmd.CommandType = CommandType.Text;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
rdr.Read();
txtSiteName.Text = rdr.GetString(0);
txtSiteAddress.Text=rdr.GetString(1);
}
}
}
}
Source:
<asp:DropDownList ID="ddlSiteID" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlSiteID_SelectedIndexChanged">
</asp:DropDownList>
<asp:TextBox ID="txtSiteName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtSiteAddress" runat="server"></asp:TextBox>
The error explains all. Your connection is closed when you call ExecuteReader. But I suppose that you are asking why?.
You think that, because you have already loaded the dropdown, then you could execute your reader without problems. But, unfortunately, the SqlDataAdapter has its own behavior when working with the connection.
From MSDN SqlDataAdapter.Fill
The Fill method retrieves rows from the data source using the SELECT
statement specified by an associated SelectCommand property. The
connection object associated with the SELECT statement must be valid,
but it does not need to be open. If the connection is closed before
Fill is called, it is opened to retrieve data, then closed. If the
connection is open before Fill is called, it remains open.
So you just need to open the connection in this way
protected void ddlSiteID_SelectedIndexChanged(object sender, EventArgs e)
{
string selectID = ddlSiteID.SelectedValue;
using(SqlConnection con = new SqlConnection(#"connectionString"))
using(SqlCommand cmd = new SqlCommand("SELECT Site_Name,Site_Address FROM tbl_Survey1 where Site_ID=#Site_ID", con))
{
con.Open();
cmd.Parameters.AddWithValue("#Site_ID", selectID);
cmd.CommandType = CommandType.Text;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
....
}
}
}
P.S. Remember to keep always your disposable objects like the connection, command and reader inside an Using block to be sure that they are closed and disposed correctly also in case of exceptions
You're missing in the second method an explicit call to open your connection:
con.Open();
Also, you don't dispose of said connection -- be careful with that. Use usings for anything that implements IDisposable:
protected void ddlSiteID_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(#"connectionString"))
{
con.Open();
string selectID = ddlSiteID.SelectedValue;
using (SqlCommand cmd = new SqlCommand("SELECT Site_Name,Site_Address FROM tbl_Survey1 where Site_ID=#Site_ID", con))
{
cmd.Parameters.AddWithValue("#Site_ID", selectID);
cmd.CommandType = CommandType.Text;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
rdr.Read();
txtSiteName.Text = rdr.GetString(0);
txtSiteAddress.Text=rdr.GetString(1);
}
}
}
}
}
You should open your connection by calling con.Open() before calling ExecuteReader in ddlSiteID_SelectedIndexChanged method. And don't forget to close it in the end.
This means your code may look like
protected void ddlSiteID_SelectedIndexChanged(object sender, EventArgs e)
{
using(var con = new SqlConnection(#"connectionString"))
{
string selectID = ddlSiteID.SelectedValue;
using (var cmd = new SqlCommand("SELECT Site_Name,Site_Address FROM tbl_Survey1 where Site_ID=#Site_ID", con))
{
cmd.Parameters.AddWithValue("#Site_ID", selectID);
cmd.CommandType = CommandType.Text;
con.Open();
try
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
rdr.Read();
txtSiteName.Text = rdr.GetString(0);
txtSiteAddress.Text=rdr.GetString(1);
}
}
}
finally
{
con.Close();
}
}
}
}
try this In SelectedIndexChanged event of DropDown.
SqlCommand requires Connection to be open
SqlConnection con = new SqlConnection(#"connectionString");
string selectID = ddlSiteID.SelectedValue;
SqlCommand cmd = new SqlCommand("SELECT Site_Name,Site_Address FROM tbl_Survey1 where Site_ID=#Site_ID", con);
cmd.Parameters.AddWithValue("#Site_ID", selectID);
cmd.CommandType = CommandType.Text;
con.open
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
rdr.Read();
txtSiteName.Text = rdr.GetString(0);
txtSiteAddress.Text=rdr.GetString(1);
}
}
}
}
con.close();
Check if your connection is open or not.
if (con != null && con.State == ConnectionState.Closed)
{
con.Open();
}
I wrote this code but I do not know why this line gives error!
String sname = dr.GetString ("name");
My code:
SqlConnection cn = new SqlConnection(
"Data Source=.;Initial Catalog=logindb;Integrated Security=True");
string query1 = "select * from tbllogin";
SqlCommand cmd = new SqlCommand(query1);
SqlDataReader dr;
try
{
cn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
String sname = dr.GetString("name");
comboBox1.Items.Add(sname);
}
}
catch (Exception e)
{
// do smth about exception
}
First of all you have to check this again:
SqlConnection cn = new SqlConnection(
"Data Source=.;Initial Catalog=logindb;Integrated Security=True");
Data Source=.; This is wrong and it will give you an error.
After that you can use the code below to achieve what you want. The code below also uses using statement to dispose the connection.
using (
SqlConnection connection = new SqlConnection(strCon)) // strCon is the string containing connection string
{
SqlCommand command = new SqlCommand("select * from tbllogin", connection);
connection.Open();
DataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
comboBox1.Items.Add(reader.GetString(int index)); // index of column you want, because this method takes only int
}
}
reader.Close();
}
(Amazingly) GetString only take an index as parameter.
See MSDN
public override string GetString(int i)
With no other signatures :-(
However you could write:
String sname = dr.Item["name"].ToString();
MSDN says that SqlDataReader.GetString method accepts an int as a parameter, which is the index of the column.
What you need is this:
while (dr.Read())
{
String sname = (string)dr["name"];
comboBox1.Items.Add(sname);
}
Here's your code:
SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=logindb;Integrated Security=True");
string query1 = "select * from tbllogin"; SqlCommand cmd = new SqlCommand(query1); SqlDataReader dr;
try {
cn.Open(); dr = cmd.ExecuteReader();
while (dr.Read())
{ String sname = (string)dr["name"];
comboBox1.Items.Add(sname);
}
}
catch (Exception e) { MessageBox.Show(e.Message, "An error occurred!"); }
The catch block wasn't written correctly, you missed the (Exception e) part.
I want to Check the "refno" already present in Tbldelivery table, If "refno" is present, then it will insert in "Tbldeliverydetails" because "refno" is primary key in 1st table. Where i check the condition ?
Here is the code i wrote in C# :
protected void btndlysave_Click(object sender, EventArgs e)
{
SqlConnection SqlCon = new SqlConnection("server=(local);Initial Catalog=TestDB;Integrated Security=SSPI;");
try
{
SqlCon.Open();
SqlCommand cmd = new SqlCommand("insert into Tbldelivery (refno,deliverdate,requestby,projectcode) values
(#refno,#deliverdate,#requestby,#projectcode) WHERE not exists (select refno from Tblinkdelivery where refno = #refno)", SqlCon);
cmd.CommandType = CommandType.Text;
if ( need check here)
cmd.Parameters.AddWithValue("#refno", txtdelrefno.Text.Trim());
cmd.Parameters.AddWithValue("#deliverdate", txtdeldate.Text.Trim());
cmd.Parameters.AddWithValue("#requestby", txtdelreq.Text.Trim());
cmd.Parameters.AddWithValue("#projectcode", ddlprojcode.Text.Trim());
}
else
{
SqlCommand cmd2 = new SqlCommand("insert into Tbldeliverdetails (refno,printercode,inkcode,quantity,price,notes) values (#refno,#printercode,#inkcode,#quantity,#price,#notes)", SqlCon);
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.AddWithValue("#refno", txtdelrefno.Text.Trim());
cmd2.Parameters.AddWithValue("#printercode", ddldelprcode.Text.Trim());
cmd2.Parameters.AddWithValue("#inkcode", ddlinkcode.Text.Trim());
cmd2.Parameters.AddWithValue("#quantity", txtdelqty.Text.Trim());
cmd2.Parameters.AddWithValue("#price", txtdelprice.Text.Trim());
cmd2.Parameters.AddWithValue("#notes", txtdelnotes.Text.Trim());
int val1 = cmd.ExecuteNonQuery();
int val2 = cmd2.ExecuteNonQuery();
}
finally
{
SqlCon.Close();
}
}
I think first of all you need to arrange your code.
Writing everything inside the button click event is not good at all. It is better if you can separate business logic and put it separately.
Try something like this.
You can create Data Access class which handle your data access.
In your Data Access Class
public SqlConnection OpenConnection()
{
try
{
var conn = new SqlConnection(“xxx”);
conn.Open();
return conn;
}
catch (Exception ex)
{
//log the exception
return null;
}
}
YourFunction(parameters)
{
var conn = OpenConnection();
if(conn != null)
{
//your code
// you can do something similar as JeremyK explained here
}
}
And in your button click
protected void btndlysave_Click(object sender, EventArgs e)
{
//CHECK THE PARAMETERS AND PASS
//DataAccess. YourFunction(parameters)
}
You query the table and see if it exists.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand sqlCommand =
new SqlCommand("SELECT * FROM dbo.Tbldelivery WHERE refno=#refno",
connection);
sqlCommand.Parameters.Add("#refno", System.Data.SqlDbType.VarChar);
sqlCommand.Parameters["#refno"].Value = refnoValue;
SqlDataReader reader = sqlCommand.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
// refno exists
}
else
{
// refno does not exist
}
}