I am c#.net newbie. This is my form table.
First Name: <asp:TextBox ID="f_name" runat="server"></asp:TextBox>
<asp:Button ID="btnInsertion" runat="server" Text="Insert"
OnClick="btnInsertion_Click" />
I need help on solving this two error in visual basic. This is my xxxx.aspx.cs which giving me two CS0103 error
-f_name does not exist in the context.
-txtFname does not exist in the context.
protected void btnInsertion_Click(object sender, EventArgs e)
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ToString();
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.Connection = connection;
cmd.CommandText = "Insert into student_folio values(#f_name)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new NpgsqlParameter(#f_name, txtFname.Text));
cmd.ExecuteNonQuery();
cmd.Dispose();
connection.Close();
txtFname.Text = ""; s
}
}
i think you have forgotten to enclose #f_name in Parameters.Add(, also txtFname is not within the scope, is it existing on the page you are accessing btnInsertion?
protected void btnInsertion_Click(object sender, EventArgs e)
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ToString();
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.Connection = connection;
cmd.CommandText = "Insert into student_folio (fieldname) values(#f_name)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new NpgsqlParameter("f_name", txtFname.Text));
cmd.ExecuteNonQuery();
cmd.Dispose();
connection.Close();
txtFname.Text = "";
}
}
Related
I have a problem with data management in the postgre database. I`m connected, now i want to add any value, but that what i wrote dosent work.
protected void Page_Load(object sender, EventArgs e)
{
try
{
Label1.Text = "Połączenie z bazą danych zakonczońe sukcesem";
NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;Database=dt_PackageWarehouse;User Id=postgres;Password=321qweQAZ");
conn.Open();
NpgsqlCommand comm = new NpgsqlCommand();
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = "select * from magazynpaczek";
NpgsqlDataAdapter nda = new NpgsqlDataAdapter(comm);
DataTable dt = new DataTable();
nda.Fill(dt);
comm.Dispose();
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception)
{
Label1.Text = "Połączenie z bazą danych zakonczońe niepowodzeniem";
}
}
protected void btnDodaj_Click(object sender, EventArgs e)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;Database=dt_PackageWarehouse;User Id=postgres;Password=321qweQAZ");
string query = "Insert into public.magazynpaczek(id, nazwafirmynadawcy, imienadawcy, nazwiskonadawcy, nrtelefonunadawcy, miastonadawcy, ulicanadawcy, nazwafirmyodbiorcy," +
" imieodbiorcy, nazwiskoodbiorcy, nrtelefonuodbiorcy, miastoodbiorcy, ulicaodbiorcy, nrprzesylki, datadoreczenia) VALUES(#NFN, #txtIN, #txtNN, #txtNTN, #txtMN," +
"#txtUN, #txtNFO, #txtIO, #txtNO, #txtNTO, #txtMO, #txtUO, #txtNP, #txtDD)";
NpgsqlCommand comm = new NpgsqlCommand(query, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
you have to create and add a parameter for each insert value:
var query = "Insert into public.magazynpaczek(id, nazwafirmynadawcy, imienadawcy, nazwiskonadawcy, nrtelefonunadawcy, miastonadawcy, ulicanadawcy, nazwafirmyodbiorcy," +
" imieodbiorcy, nazwiskoodbiorcy, nrtelefonuodbiorcy, miastoodbiorcy, ulicaodbiorcy, nrprzesylki, datadoreczenia) VALUES(#NFN, #txtIN, #txtNN, #txtNTN, #txtMN," +
"#txtUN, #txtNFO, #txtIO, #txtNO, #txtNTO, #txtMO, #txtUO, #txtNP, #txtDD)";
IDbCommand command = conn.CreateCommand();
command.CommandText = query;
var parameter = command.CreateParameter();
parameter.ParameterName = "NFN";
parameter.Value = nfn;
command.Parameters.Add(parameter);
parameter = command.CreateParameter();
parameter.ParameterName = "txtIN";
parameter.Value = txtIN.text;
command.Parameters.Add(parameter);
.... and so on
conn.Open();
command.ExecuteNonQuery();
conn.Close();
I am getting the error:
An unhandled exception of type 'System.InvalidOperationException'
occurred in MySql.Data.CF.dll
in my windows application program.
Below is my code.
In app.config:
inside connectionStrings tag
add name="ConnectionString"
connectionString="server=localhost;database=my_db;user=root;port=3306;
password=mypwd;
In LoginForms.cs
using System.Configuration;
using MySql.Data.MySqlClient;
namespace MySoftware
{
public partial class Login : Form
{
MySqlConnection conn;
public static int valid = 0;
public Login()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{
var connectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new MySqlConnection(connectionString);
conn.open();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "Verify_Login";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#uname", textBox1.Text);
cmd.Parameters["#uname"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#pwd", textBox2.Text);
cmd.Parameters["#pwd"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#result", MySqlDbType.Int32);
cmd.Parameters["#result"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery(); // At this line the error is thrown
int valid = (int)(cmd.Parameters["#result"].Value);
}
}
}
Verify_Login is a stored procedure which is created in MySQL as below.
CREATE PROCEDURE `Verify_Login`(in uname varchar(20),in pwd varchar(20),out
result bool)
BEGIN
select count(*) into result from Login where uname=uname and password=pwd;
END
Could anyone please help me with this?
Your code fails because is trying to execute a command and this command is not bound to an open connection. You have a lot of ways to bind the connection
MySqlCommand cmd = conn.CreateCommand();
or
MySqlCommand cmd = new MySqlCommand(sqlText, conn);
or
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
Of course the suggestion to use the appropriate Connector for your environment still stands....
Your code refactored a bit
private void btnLogin_Click(object sender, EventArgs e)
{
var connectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using(MySqlConnection conn = new MySqlConnection(connectionString))
using(MySqlCommand cmd = new conn.CreateCommand())
{
conn.open();
cmd.CommandText = "Verify_Login";
cmd.CommandType = CommandType.StoredProcedure;
.....
cmd.ExecuteNonQuery();
int valid = (int)(cmd.Parameters["#result"].Value);
}
}
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'm a new coder trying to code C# to insert data into sqlworkbench database. Having alot of problems. Looking for any help. Thanks.
private void enterbutton_Click(object sender, EventArgs e)
{
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=;database=mydb;";
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("insert into garden(idGarden) VALUES (#idGarden)");
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#idGarden", gardentextBox.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
SqlCommand cmd1 = new SqlCommand("insert into rainfall(aveRainfall) VALUES (#aveRainfall)");
cmd1.Connection = conn;
cmd1.Parameters.AddWithValue("#aveRainfall", aveRaintextBox.Text);
cmd1.ExecuteNonQuery();
cmd1.Parameters.Clear();
SqlCommand cmd2 = new SqlCommand("insert into seat(idSeat) VALUES (#idSeat)");
cmd2.Connection = conn;
cmd2.Parameters.AddWithValue("#idSeat", seatIDtextBox.Text);
cmd2.ExecuteNonQuery();
cmd2.Parameters.Clear();
SqlCommand cmd3 = new SqlCommand("insert into temperature(currentTemp) VALUES (#currentTemp)");
cmd3.Connection = conn;
cmd3.Parameters.AddWithValue("#currentTemp", currentTemptextBox.Text);
cmd3.ExecuteNonQuery();
cmd3.Parameters.Clear();
conn.Close();
}
You didn't connect your SqlCommand's with your MySqlConnection. And I think they should MySQLSqlCommand instead of SqlCommand.
You can assing their .Connection properties to your MySqlConnection. Like;
cmd.Connection = conn;
cmd2.Connection = conn;
cmd3.Connection = conn;
cmd4.Connection = conn;
And you try to execute your cmd only. I think you should execute your all others commands like cmd2, cmd3 and cmd4..
cmd.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
cmd3.ExecuteNonQuery();
cmd4.ExecuteNonQuery();
And could be better to use using statement to dispose your database connections..
using(MySqlConnection conn = new MySqlConnection(myConnectionString))
using(MySQLCommand cmd = conn.CreateCommand())
{
//
}
Also always prefer to use Add() instead of AddWithValue().
Read: http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
I read some data from a table and after that I want to edit it, and then insert edited data to the database. I wrote this code but after runing it, old data inserts into database.
What should I do?
Here is my code;
protected void Page_Load(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = new SqlConnection(Class1.CnnStr);
SqlDataReader reader;
cmd.CommandText = "select ChequeNo,ChequeDate from table where Number=#Number";
cmd.Connection.Open();
cmd.Parameters.AddWithValue("#Number", Number_lbl.Text);
reader = cmd.ExecuteReader();
if (reader.Read())
{
ChequeNo_txt.Text = reader["ChequeNo"].ToString();
ChequeDate_txt.Text = reader["ChequeDate"].ToString();
reader.Close();
}
cmd.Connection.Close();
}
protected void SAVE_bt_Click(object sender, EventArgs e)
{
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = new SqlConnection(Class1.CnnStr);
cmd1.Connection.Open();
cmd1.Parameters.AddWithValue("#Number", Number_lbl.Text);
cmd1.CommandText ="update table set chequeNo=#ChequeNo,ChequeDate=#ChequeDate
where Number=#Number";
cmd1.Parameters.AddWithValue("#ChequeNo",ChequeNo_txt.Text);
cmd1.Parameters.AddWithValue("#ChequeDate", ChequeDate_txt.Text);
cmd1.ExecuteNonQuery();
}
You should only read from database if !Page.IsPostback:
if (!IsPostBack)
SqlCommand cmd = new SqlCommand();
cmd.Connection = new SqlConnection(Class1.CnnStr);
SqlDataReader reader;
cmd.CommandText = "select ChequeNo,ChequeDate from table where Number=#Number";
cmd.Connection.Open();
cmd.Parameters.AddWithValue("#Number", Number_lbl.Text);
reader = cmd.ExecuteReader();
if (reader.Read())
{
ChequeNo_txt.Text = reader["ChequeNo"].ToString();
ChequeDate_txt.Text = reader["ChequeDate"].ToString();
reader.Close();
}
cmd.Connection.Close();
}
Otherwise you are overwriting all changes and bind the controls to the old values.
http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx