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
Related
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 want to insert some data into Database Using C#
But I get below error
Error:Data type Mismatch when try to Execute
cmd1.ExecuteNonQuery();
private void btnFirst_Click(object sender, EventArgs e)
{
conString =Properties.Settings.Default.TransportationConnectionString;
con.ConnectionString = conString;
System.Data.OleDb.OleDbCommand cmd1 = new System.Data.OleDb.OleDbCommand();
cmd1.Connection = con;
cmd1.CommandText = "INSERT INTO [BillingGrd] ([InvoiceNo],[FromLocation],[ToLocation],[Material],[Trip],[MetricTon],[BillWeight],[Rate],[BillAmount],[GrandTotal]) Values (#InvoiceNo,#FromLocation,#ToLocation,#Material,#Trip,#MetricTon,#BillWeight,#Rate,#BillAmount,#GrandTotal)";
for(inc=0;inc<listView1.Items.Count;inc++)
{
cmd1.Parameters.AddWithValue("#InvoiceNo", txtBilNo.Text);
cmd1.Parameters.AddWithValue("#FromLocation", listView1.Items[inc].SubItems[0].Text);
cmd1.Parameters.AddWithValue("#ToLocation", listView1.Items[inc].SubItems[1].Text);
cmd1.Parameters.AddWithValue("#Material", listView1.Items[inc].SubItems[2].Text);
cmd1.Parameters.AddWithValue("#Trip", listView1.Items[inc].SubItems[3].Text);
cmd1.Parameters.AddWithValue("#MetricTon", listView1.Items[inc].SubItems[4].Text);
cmd1.Parameters.AddWithValue("#BillWeight", listView1.Items[inc].SubItems[5].Text);
cmd1.Parameters.AddWithValue("#Rate", listView1.Items[inc].SubItems[6].Text);
cmd1.Parameters.AddWithValue("#BillAmount", listView1.Items[inc].SubItems[7].Text);
cmd1.Parameters.AddWithValue("#GrandTotal", textBox1.Text);
}
con.Open();
cmd1.ExecuteNonQuery();//error here datatype mismatch
con.Close();
}
Try This might be work for you.....
if not Then let me know by comment
private void btnFirst_Click(object sender, EventArgs e)
{
conString =Properties.Settings.Default.TransportationConnectionString;
con.ConnectionString = conString;
System.Data.OleDb.OleDbCommand cmd1 = new System.Data.OleDb.OleDbCommand();
cmd1.Connection = con;
for(inc=0;inc<listView1.Items.Count;inc++)
{
cmd1.CommandText="";
con.Open();
cmd1.CommandText = "INSERT INTO [BillingGrd] ([InvoiceNo],[FromLocation],[ToLocation],[Material],[Trip],[MetricTon],[BillWeight],[Rate],[BillAmount],[GrandTotal]) Values ('"+txtBilNo.Text+"','"+listView1.Items[inc].SubItems[0].Text+"','"+listView1.Items[inc].SubItems[1].Text+"','"+listView1.Items[inc].SubItems[2].Text+"','"+listView1.Items[inc].SubItems[3].Text+"','"+listView1.Items[inc].SubItems[4].Text+"','"+listView1.Items[inc].SubItems[5].Text+"','"+listView1.Items[inc].SubItems[6].Text+"','"+listView1.Items[inc].SubItems[7].Text+'")";
cmd1.ExecuteNonQuery();//error here datatype mismatch
con.Close();
}
}
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();
}
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\ExportPagetoPDFinASP.Net\App_Data\abcc.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM cookbook";
cmd.Connection = con;
cmd.ExecuteReader();
}
Not able to fetch data. i don't know what is wrong.
ExecuteReader would return you a DataReader, you need to iterate it and get rows from your command.
You can also use a DataTable to fill the rows from DataReader like:
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
You can have the following code:
using (SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\ExportPagetoPDFinASP.Net\App_Data\abcc.mdf;Integrated Security=True;User Instance=True"))
{
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT * FROM cookbook";
cmd.Connection = con;
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
}
}
Consider using using statement with your Connection and Command objects.
You can iterate rows returned from DataReader like:
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0])); //prints first column
}
public string Log(int userResult)
{
string result = "result saved";
using (var conn = new SqlConnection("Data Source=XXXX;InitialCatalog=XXXX;Integrated Security=True"))
{
using (var cmd = new SqlCommand())
{
cmd.CommandText = "dbo.setCalculatorResult";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("RESULT", userResult);
if (conn.State != ConnectionState.Open)
conn.Open();
int rowCount = cmd.ExecuteNonQuery();
if (rowCount == 0)
result = "there was an error";
}
}
return result;
}
and also consider using procs
private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand cmd = new OleDbCommand("select project_name, ID from tb_project", con);
con.Open();
OleDbDataReader DR = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(DR);
combo_status.DataSource = table;
combo_status.DisplayMember = "project_name";
combo_status.ValueMember = "ID";
combo_status.Text = "Select Project Name";
}
private void btnSave_Click_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand("Insert Into tb1(name) Values (#name)", con);
cmd.Parameters.AddWithValue("name", combo_status.SelectedValue);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
}
In the first class i have a combobox and i am fetching its value from database and i have shown "Select Project Name" on page load in combobox.I want to insert its value only when user selects option from dropdown and insert nothing if user did not choose any option.
Now the problem is that the first name in the dropdown gets inserted on button click.without choosing any option.I want that if user did not choose any name value from dropdown nothing should get inserted.
can anyone help me..?
Assuming that datatype of ID column is int:
private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand cmd = new OleDbCommand("select project_name, ID from tb_project", con);
con.Open();
OleDbDataReader DR = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(DR);
//begin adding line
DataRow row = table.NewRow();
row["project_name"] = "Select Project Name";
row["ID"] = 0;
table.Rows.InsertAt(row, 0);
//end adding line
combo_status.DataSource = table;
combo_status.DisplayMember = "project_name";
combo_status.ValueMember = "ID";
combo_status.Text = "Select Project Name";
}
private void btnSave_Click_Click(object sender, EventArgs e)
{
if(combo_status.SelectedValue == 0)
{
return; //do nothing if user didn't select anything in combobox, you can change this line of code with whatever process you want
}
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand("Insert Into tb1(name) Values (#name)", con);
cmd.Parameters.AddWithValue("name", combo_status.SelectedValue);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
}
Hope this will help you