SQL Row Updating Not Working in C# - c#

I can't figure out why the following code is not updating either my GridView nor my MySQL Database. Can anyone offer me some tips as to what I may be doing incorrectly?
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
connection();
GridViewRow row = GridView1.Rows[e.RowIndex];
Label lblID = (Label)row.FindControl("lblID");
TextBox textName = (TextBox)row.Cells[3].Controls[0];
TextBox textadd = (TextBox)row.Cells[4].Controls[0];
TextBox textc = (TextBox)row.Cells[5].Controls[0];
String query = "update employeeDB set [First Name:]='" + textName.Text + "', [Last Name:]='" + textadd.Text + "', [Email:]='" + textc.Text + "' where id='" + lblID + 1 + "'";
SqlCommand com = new SqlCommand(query, con);
SqlDataReader dr;
dr = com.ExecuteReader();
GridView1.EditIndex = -1;
bind();
}
Here is my bind method as requested:
private void bind()
{
connection();
string query = "select * from employeeDB where [Last Name:] like'" + TextBox1.Text + "%'";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}

Replace
dr = com.ExecuteReader();
with
com.ExecuteNonQuery();
ExecuteReader is for SELECT queries.
Also, in real world application you should not build sql string like you do. Use SqlParameter instead to avoid sql injection and many other errors.

GridViewRow row = GridView1.Rows[e.RowIndex];
Label lblID = (Label)row.FindControl("lblID");
TextBox textName = (TextBox)row.Cells[3].Controls[0];
TextBox textadd = (TextBox)row.Cells[4].Controls[0];
TextBox textc = (TextBox)row.Cells[5].Controls[0];
/*are you sure column names are like [First Name:],[Last Name:] and [Email:] in the table*/
/*Syntax for update command should be like this "UPDATE TableName SET ColumnName1=#Parameter1, ColumnName2=#Parameter2 ....
* WHERE ColumnName=#ParameterName"
*/
String query = "update employeeDB set [First Name:]=#FirstName, [Last Name:]=#LastName, [Email:]=#Email where id=#id";
SqlCommand com = new SqlCommand(query, con);
com.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = textName.Text;
com.Parameters.Add("#LastName", SqlDbType.VarChar).Value = textadd.Text;
com.Parameters.Add("#Email", SqlDbType.VarChar).Value = textc.Text;
com.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32(lblID.Text) + 1;
con.Open();
com.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
bind();
}

you should be doing something like this
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["TaskTable"];
//Update the values.
GridViewRow row = TaskGridView.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["Id"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Description"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["IsComplete"] = ((CheckBox)(row.Cells[3].Controls[0])).Checked;
//Reset the edit index.
TaskGridView.EditIndex = -1;
//Bind data to the GridView control.
BindData();

What are you getting now? Exception or just no error and nothing is happening? Things to check are db connection string-make sure your connection string is pointing to the db you are targeting. And second i would like to point out that the query is open for sql injection attack (something you need to consider - if you are going to use it to production code).Third, what do you have in the bind method? What data source its trying to bind and with what control? From the sample code itself, it looks like no data is being returned from db.
Updated with:
And by the way, should the colon be there in your query? See for instance the colon after first name ([First Name:] ) String query = "update employeeDB set [First Name:]='" + textName.Text + "', [Last Name:]='" + textadd.Text + "', [Email:]='" + textc.Text + "' where id='" + lblID + 1 + "'";

Related

Data receiving from excel column and show them in texboxes when value in combo box changed

Data receiving from excel column and change them when value in combo box changed.
Here is the code :
private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
con.Open();
str = "select * from [Sac Haddehanesi Kalite Kontrol] where [Bobin ID]='" + comboBox1.Text.Trim() + "'";
com = new OleDbCommand(str, con);
OleDbDataReader reader = com.ExecuteReader();
if (reader.Read())
{
comboBox1.Text = reader["Bobin ID"].ToString();
textBox1.Text = reader["Slab ID"].ToString();
textBox2.Text = reader["Döküm Kalitesi"].ToString();
textBox3.Text = reader["Sipariş Çelik Kalitesi"].ToString();
textBox4.Text = reader["Standart Kalite Adı"].ToString();
textBox5.Text = reader["Bobin Planlanan Kalınlık (mm)"].ToString();
}
con.Close();
reader.Close();
}
Any Help will be highly appreciated......
Thank u
Excel Sheets names end with a $ and when a sheet's name has spaces in it you must enclose it in single quotes. Thus your SQL should read...
Select * From ['Sac Haddehanesi Kalite Kontrol$']
You should parameterise your query so properly it will be...
Select * From ['Sac Haddehanesi Kalite Kontrol$'] Where [Bobin ID] = ?
OLEDB parameters are positional rather than named (as in SQL/Server). i.e. you specify them in the order they appear in the query.
Thus your code becomes...
OleDbCommand com = new OleDbCommand("Select * From ['Sac Haddehanesi Kalite Kontrol$'] Where [Bobin ID] = ?", conn);
com.Parameters.Add("?", OleDbType.VarChar).Value = "abc";
OleDbDataReader reader = com.ExecuteReader();
You can go through the tables in the workbook by...
DataTable TablesList = conn.GetSchema("Tables");
foreach (DataRow TableRow in TablesList.Rows)
{
if (TableRow["TABLE_NAME"].ToString().EndsWith("$") | TableRow["TABLE_NAME"].ToString().EndsWith("$'"))
{
// Handle the Excel Sheet
}
}
Incidentally you don't show us your connection string in your code. Here's the one I used for the above...
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Test.xlsx;Extended properties='Excel 12.0;HDR=Yes;IMEX=1'";

Data type mismatch in criteria expression(Convert.ToInt32(cmd.ExecuteScalar());)

I am trying to Display a name in the textbox from the database if the ID entered by the user matches the record in the MS ACCESS DATABASE.
I'm getting the error Data type mismatch in criteria expression at the line int count = Convert.ToInt32(cmd.ExecuteScalar());
The following is my aspx.cs code-
protected void Button1_Click(object sender, EventArgs e)
{
clear();
idcheck();
DataTable dt = new DataTable();
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT [DoctorName] FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
TextBox2.Text = dr["DoctorID"].ToString();
dr.Close();
con.Close();
}
}
public void idcheck()
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT count(DoctorName) FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count > 0)
{
Label21.Text = "Doctor Name";
}
else
{
Label21.Text = "Id Does not Exist";
}
}
void clear()
{
TextBox2.Text = "";
}
I guess that is because you as passing in an ID, which is usually a numeric value, as a text field:
DoctorID='" + TextBox1.Text.Trim() + "'
Which should be:
DoctorID=" + TextBox1.Text.Trim()
Another problem arises, since you are vulnerable to SQL injection. What if the text box contained 1; delete users? Then your entire users table would be empty. The lesson learned: use parameterized queries!
Then you can express the SQL as:
DoctorID= ?
And add the parameter to the request:
cmd.Parameters.AddWithValue("?", TextBox1.Text.Trim());

I have values in database still cannot retrieve them in window form

I am trying to retrieve values from tables in the database but can not do so.
Here is my code
int crs_Id = Convert.ToInt32(Session["crs_id"]);
SqlDataReader r1, r2, r3;
con.Open();
SqlCommand cmd2 = new SqlCommand("Select Course_Title, Description from COURSE where course_ID='" + crs_Id + "'", con);
r1 = cmd2.ExecuteReader();
Label5.Text = r1["Course_Title"].ToString();
Label6.Text = r1["Description"].ToString();
r1.Close();
SqlCommand cmd3 = new SqlCommand("Select Tutor_ID from Teaching where course_ID='" + crs_Id + "'", con);
r2 = cmd3.ExecuteReader();
if (r2.Read())
{
int tutor = Convert.ToInt32(r2["Tutor_ID"]);
r2.Close();
SqlCommand cmd4 = new SqlCommand("Select Tutor_Name from TUTOR where Tutor_Id='" + tutor + "'", con);
r3 = cmd4.ExecuteReader();
Label7.Text = "Tutor Name is " + r3["Tutor_Name"].ToString() + "";
r3.Close();
}
else
r2.Close();
I am getting the exception as shown in the screenshot
You're getting the error because you're not reading the first row into the SqlDataReader returned from ExecuteReader. You can check r1.HasRows property and only access the columns if rows were returned. You also need to execute r1.Read() to get the first row.
r1 = cmd2.ExecuteReader();
if ( r1.HasRows )
{
r1.Read();
Label5.Text = r1["Course_Title"].ToString();
Label6.Text = r1["Description"].ToString();
}
else
{
Label5.Text = "";
Label6.Text = "";
}

Using ExecuteReader instead of SQLDataAdapter

I've got a C# project where I'm trying to export the results of a datagrid. Sometimes the data gets quite large, so rather than re-executing the code I want to dump the dataset into a session variable.
This works perfectly in most of my projects. One example from a project where I use this is:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sqlconnectionStatus = new SqlConnection(str);
string DDL_Value = Convert.ToString(Request.QueryString["DDL_Val"]);
//Use the ClassTesting class to determine if the dates are real, and fill in today's date if they're blank
string StDt_Value = ClassTesting.checkFields(Request.Form["txtStartDate"], "Date");
string EnDt_Value = ClassTesting.checkFields(Request.Form["txtEndDate"], "Date");
//string StDt_Value = Convert.ToString(Request.QueryString["StDt_Val"]);
//string EnDt_Value = Convert.ToString(Request.QueryString["EnDt_Val"]);
string BTN_Value;
// Because the date is stored as an INT, you have to request the string and then
// convert it to an INT
string StDT_Vals = Request.QueryString["StDt_Val"].ToString();
string EnDT_Vals = Request.QueryString["EnDt_Val"].ToString();
//sqlquery = "Select PROC_NM as 'Agent Name', AdminLevel as Role, Count(Claim_ID) as 'Count of Claims Reviewed', Spare as AgentID ";
//sqlquery = sqlquery + "from ClosedClaims_MERGE CCM ";
sqlquery = "Select PROC_NM as 'Agent Name', AdminLevel as Role, Count(DISTINCT Claim_ID) as 'Count of Claims Reviewed', Spare as AgentID ";
sqlquery = sqlquery + "from (SELECT DISTINCT Spare, SpareFinished, CLAIM_ID FROM ClosedClaims_MERGE ";
sqlquery = sqlquery + "UNION SELECT DISTINCT Spare, SpareFinished, CLAIM_ID FROM tblAuditing) CCM ";
sqlquery = sqlquery + "LEFT JOIN PROC_LIST PL ON CCM.Spare = PL.LOGIN ";
sqlquery = sqlquery + "WHERE CCM.SpareFinished >= '" + StDt_Value + "' AND CCM.SpareFinished <= '" + EnDt_Value + "' ";
sqlquery = sqlquery + "GROUP BY Spare, PROC_NM, AdminLevel ";
sqlquery = sqlquery + "ORDER BY Count(Claim_ID) DESC";
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(sqlquery, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// Fill the DataSet.
DataSet ds = new DataSet();
adapter.Fill(ds, "dsEffVol");
// Add this to a session variable so the datagrid won't get NULLed out on repost
Session["SSEffVol"] = ds;
// Perform the binding.
grdEffVol.Attributes.Add("style", "overflow:auto");
//GridView_WODetails.Attributes.Add("style", "table-layout:fixed");
grdEffVol.AutoGenerateColumns = true;
grdEffVol.DataSource = ds;
grdEffVol.DataBind();
}
I've got a new project where I'm not using SQL strings, but instead I'm pulling data based on SQL Server Stored Procedures. The code block there is:
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
List<ReportData> myReportData = new List<ReportData>();
using (SqlConnection connection1 = new SqlConnection(str2))
{
//Query the Reports table to find the record associated with the selected report
using (SqlCommand cmd = new SqlCommand("SELECT * from RM_tblManagerReports WHERE ReportID = " + cboFilterOption.SelectedValue + "", connection1))
{
connection1.Open();
using (SqlDataReader DT1 = cmd.ExecuteReader())
{
while (DT1.Read())
{
//Read the record into an "array", so you can find the SProc and View names
int MyRptID = Convert.ToInt32(DT1[0]);
string MyRptName = DT1[1].ToString();
string MyRptSproc = DT1[2].ToString();
string MySQLView = DT1[3].ToString();
string MyUseDates = DT1[4].ToString();
//Run the Stored Procedure first
SqlConnection connection2 = new SqlConnection(str2);
SqlCommand cmd2 = new SqlCommand();
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.CommandText = "" + MyRptSproc + "";
cmd2.Connection = connection2;
//Set up the parameters, if they exist
if (MyUseDates != "N")
{
cmd2.Parameters.Add("#StDate", SqlDbType.Date).Value = DateTime.Parse(txtStDate.Value);
cmd2.Parameters.Add("#EnDate", SqlDbType.Date).Value = DateTime.Parse(txtEnDate.Value);
}
else
{
}
try
{
connection2.Open();
GridView_Reports.EmptyDataText = "No Records Found";
SqlDataReader dr = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
Session["SSRptMenu"] = dr;
GridView_Reports.DataSource = dr;
GridView_Reports.DataBind();
// Add this to a session variable so the datagrid won't get NULLed out on repost
GridView_Reports.DataBound += GridView_Reports_RowDataBound;
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(btnSubmit, typeof(Button), "Report Menu", "alert('There is no View associated with this report.\\nPlease contact the developers and let them know of this issue.')", true);
Console.WriteLine(ex);
return;
}
finally
{
connection2.Close();
connection2.Dispose();
}
}
}
}
}
}
I'm kind of guessing my way through this, and I'm not sure if I'm reading the data into a dataset properly. The page is shutting down, and I'm pretty sure the problem is in the lines:
SqlDataReader dr = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
Session["SSRptMenu"] = dr;
GridView_Reports.DataSource = dr;
Quite honestly, I've googled SqlDataReader vs SqlDataAdapter and can't really find anything, but I need to fill the session variable in the second example and also have the datagrid populate properly. So, in essence, I need to put the results of a Stored Procedure into a dataset. Can anyone offer suggestions on what I'm doing wrong?
I'm pretty sure most controls don't accept readers in their DataSource property. Plus the majority of readers are forward-only, so although you're trying to store the reader as a session variable, chances are you would only be able to read it once.
Why do you want to use a reader for this when your post seems to indicate that you know you need to use a DataSet? Why not just use an adapter the way you show in your first post? Adapters work fine with commands that use sprocs.
Instead of:
SqlDataReader dr = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
Session["SSRptMenu"] = dr;
GridView_Reports.DataSource = dr;
Just use:
var adapter = new SqlDataAdapter(cmd2);
var ds = new DataSet();
adapter.Fill(ds, "MyTableName");
Session["SSRptMenu"] = ds;
GridView_Reports.DataSource = ds;

c# How to insert textbox value and save it to sql database?

How to insert textbox value and save it to sql database?
I need some help here regarding to the question above. When I clicked button save, it should update the input textbox to the sql database Workers. Could you guys make some coding sample to achieve this? Because what I do is not working at all. This is the coding :
private void btnSave_Click(object sender, EventArgs e) {
#region SaveButton
// System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter ();
//System.Data.SqlClient.SqlCommandBuilder cb;
//cb = new System.Data.SqlClient.SqlCommandBuilder (da);
//add to Dataset a new row
DataRow dRow = ds1.Tables["Workers"].NewRow();
//add data to the new row just have been created
//refer to first_Name
dRow[1] = textBox1.Text;
dRow[2] = textBox2.Text;
dRow[3] = textBox3.Text;
//add command
//add to table worker a new row that declared by row variable name dRow
ds1.Tables["Workers"].Rows.Add(dRow);
MaxRows = MaxRows + 1; //to enable last row is still last row
inc = MaxRows - 1;
//call data adapter da to update and save data into database sql server
//da.Update(ds1, "Workers");
MessageBox.Show("Entry Added!");
#endregion
con.ConnectionString = "Data Source=.\\SQLEXPRESS; AttachDbFilename =D:\\MyWorkers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
string strSQL = "INSERT INTO Workers (first_Name, last_Name, job_Title )" + " VALUES ('" + textBox1.Text + "', '" + textBox2.Text + "', " + " '" + textBox3.Text + "') ";
con.Close();
}
I have solved this question by connecting properly to the Workers database. YeaY!!
Here's the right code for this question:
private void btnSave_Click(object sender, EventArgs e)
{
#region SaveButton
System.Data.SqlClient.SqlDataAdapter da;
string sql = "SELECT * From tblWorkers";
da = new System.Data.SqlClient.SqlDataAdapter(sql, con);
System.Data.SqlClient.SqlCommandBuilder cb;
cb = new System.Data.SqlClient.SqlCommandBuilder (da);
//add to Dataset a new row
DataRow dRow = ds1.Tables["Workers"].NewRow();
//add data to the new row that has just been created
//refer to first_Name
dRow[1] = textBox1.Text;
dRow[2] = textBox2.Text;
dRow[3] = textBox3.Text;
//add command
//add to table worker a new row that declared by row variable name dRow
ds1.Tables["Workers"].Rows.Add(dRow);
MaxRows = MaxRows + 1; //to enable last row is still last row
inc = MaxRows - 1;
//call data adapter da to update and save data into database sql server
da.Update(ds1, "Workers");
MessageBox.Show("Entry Added!");
con.Close();
#endregion
You'll need to Execute non query
Source
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}

Categories

Resources