I have the following C# to UPDATE a record, however the textbox shows, but doesn't update to the database. Likewise, I cannot ADD a record either.
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
Add:
protected void AddNewMainPost(object sender, EventArgs e)
{
string postID = ((TextBox)GridView1.FooterRow.FindControl("txtPostID")).Text;
string Name = ((TextBox)GridView1.FooterRow.FindControl("txtSelect")).Text;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into homepageSelection(postID, selectionText) " +
"values(#postID, #selectionText,);" +
"select postID,selectionText, from homepageSelection";
cmd.Parameters.Add("#postID", SqlDbType.VarChar).Value = postID;
cmd.Parameters.Add("#selectionText", SqlDbType.VarChar).Value = Name;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
Update
protected void UpdateMainPost(object sender, GridViewUpdateEventArgs e)
{
string postID = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblpostID")).Text;
string Name = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtSelec")).Text;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update homepageSelection set selectionText=#selectionText, " +
"where postID=#postID;" +
"select postID,selectionText from homepageSelection";
cmd.Parameters.Add("#postID", SqlDbType.VarChar).Value = postID;
cmd.Parameters.Add("#selectionText", SqlDbType.VarChar).Value = Name;
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
I have two fields in the database:
Table: homepageSelection Fields: postID and selectionText
As I can see from your code above, you have a syntax error in both queries, but most important thing is the fact that you don't associate your command to the connection. Thus, unless you recreate the connection inside the GetData method, your command cannot be executed.
So, to fix the syntax errors
"select postID,selectionText from homepageSelection";
^^^ comma not valid here
cmd.CommandText = #"update homepageSelection set
selectionText=#selectionText" +
^^^^ again comma not valid here
cmd.CommandText = "insert into homepageSelection(postID, selectionText) " +
"values(#postID, #selectionText);" +
^^^ no comma here
EDIT: it seems that you create the connection inside the GetData method, thus you don't need it in the two calling methods.
Related
This Messages form display table with these informations (ID,FROM,TO,TITLE,MESSAGE).
I am trying to search for all the messages send to a certain user . user will enter his name in the Search_textBox then it will filter the table to keep only messages to this user.
private void Search_button_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = cmd.CommandText = "Select * from MessagesTable where To =" + Search_textBox.Text;
cmd.Parameters.AddWithValue("#To", Search_textBox.Text);
DataSet dataSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
}
I get this error :
System.Data.SqlClient.SqlException: 'Invalid column name 'To'.'
What does the "search_name" parameter contains? The Message? The Column Name?
Your query is
Select * from MessagesTable where " + search_name + " = #From"
Then you specifies the "search_name" as a parameter for the #From...
So I believe your input was "Name" and your query is looked like this now:
Select * from MessagesTable where Name = 'Name';
You do not have any Name column in this specified table as you described.
this is Correct
private void Search_button_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from MessagesTable where [To]= #To";
cmd.Parameters.AddWithValue("#To", Search_textBox.Text);
DataSet dataSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
}
You can change it as follows. Of course, if I understand correctly, that you want to search in the messages field by the input you get from the user.
private void Search_button_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from MessagesTable where MESSAGE = #From";
cmd.Parameters.AddWithValue("#From", search_name);
DataSet dataSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
}
Try with To, because "To" - keyword SQL:
cmd.CommandText = cmd.CommandText = "Select * from MessagesTable where [To] =" + Search_textBox.Text;
this combo box gets the job id from the database and assigns it to the jobidcombobox.
private void filljobid()
{
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT job_id FROM job";
DataSet ds = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(ds);
con.Close();
jobidcombobox.DisplayMember = "job_id";
jobidcombobox.ValueMember = "job_id";
jobidcombobox.DataSource = ds.Tables[0];
}
And then this indexchange code takes the jobidcombobox value and uses it it to query to get the rest of the columns that relate to it.
private void jobidcombobox_SelectedIndexChanged(object sender, EventArgs e)
{
string JobID = jobidcombobox.Text;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * from job where job_id = '" + JobID + "' ";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
customeridcombobox.Text = ds.Tables[0].Rows[0]["customer_id"].ToString();
depotidcombobox.Text = ds.Tables[0].Rows[0]["depot_id"].ToString();
startlocationtextbox.Text = ds.Tables[0].Rows[0]["start_location"].ToString();
endlocationtextbox.Text = ds.Tables[0].Rows[0]["end_location"].ToString();
jobtypecombobox.Text = ds.Tables[0].Rows[0]["job_type"].ToString();
}
else
{
MessageBox.Show("Invalid job number");
}
}
As seen above the customerid is filled but only with a single value which relates to the jobid. I would like to add other customer id values in here from the database. I have tried to same function as jobid to get the customer id but i cant make it relate to the job id.
Is there any way to do this?
Try this...
Fill the job id and customer id boxes.
private void FillJobIdAndCustomerId()
{
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT job_id, customer_id FROM job";
DataSet ds = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(ds);
con.Close();
var dataRows = ds.Tables[0].AsEnumerable();
jobidcombobox.DisplayMember = "job_id";
jobidcombobox.ValueMember = "job_id";
jobidcombobox.DataSource = dataRows.Select(x=>x.job_id);
customeridcombobox.DisplayMember = "customer_id";
customeridcombobox.ValueMember = "customer_id";
customeridcombobox.DataSource = dataRows.Select(x=>x.customer_id);
}
And then when the a job id is selected...
private void jobidcombobox_SelectedIndexChanged(object sender, EventArgs e)
{
string JobID = jobidcombobox.Text;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * from job where job_id = #jobId";
commandObject.Parameters.AddWithValue("#jobId", JobID);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
customeridcombobox.SelectedIndex = customeridcombobox.FindString(ds.Tables[0].Rows[0]["customer_id"].ToString());
depotidcombobox.Text = ds.Tables[0].Rows[0]["depot_id"].ToString();
startlocationtextbox.Text = ds.Tables[0].Rows[0]["start_location"].ToString();
endlocationtextbox.Text = ds.Tables[0].Rows[0]["end_location"].ToString();
jobtypecombobox.Text = ds.Tables[0].Rows[0]["job_type"].ToString();
}
else
{
MessageBox.Show("Invalid job number");
}
}
Can follow similar pattern for other combo boxes you have (dept, jobtype from your example) if you would like to.
Note: You may have observed that I changed the query building slightly, using SqlParameters. The way it was written in your sample code is a classic case of SQL Injection.
I have a problem , i'm trying to do operations between values recorded(type float) in table of data , the problem is when i try to update value(result of the operation in textbox) in datable using combobox after maintaining opération , it shows me error (System.Data.SqlClient.SqlException: 'Error converting data type varchar to float.'), So how can i resolve that !help please
This is a part a of my code in which the error exists
private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{
con.Open();
String query = "UPDATE Table_com SET Contents='" + textBox6.Text + "' WHERE Variable='" + comboBox5.Text + "'";
SqlDataAdapter SDA = new SqlDataAdapter(query, con);
SDA.SelectCommand.ExecuteNonQuery();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from Table_com where Variable='" + comboBox5.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
MessageBox.Show("Variable mise à jour avec succés");
}
You cannot use float integer etc. values like text field as:
String query = "UPDATE Table_com SET Contents='" + textBox6.Text + "' WHERE Variable='" + comboBox5.Text + "'";
and your code really risky, you may use parameters like this, dont use string and convert your value to float :
static void Main(string[] args)
{
var ConnectionString = "YOUR CONNECTION STRING";
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
String query = "UPDATE Table_com SET Contents=#contents WHERE Variable=#variable";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("#contents", SqlDbType.Float).Value = Convert.ToDouble(textBox6.Text);
cmd.Parameters.Add("#variable", SqlDbType.NVarChar).Value = comboBox5.Text;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
}
this is what i tried refering to wikiCan answer
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-VEFPLGG\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
String query = "UPDATE Table_com SET Contents=#contents ";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("#contents", SqlDbType.Float).Value = textBox6.Text;
//cmd.Parameters.Add("#variable", SqlDbType.Float).Value = Convert.ToDouble(comboBox5.Text);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string query = "select * from aspnet_Users where userName like '%#UserName%'";
connection.Open();
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.Add("#UserName", SqlDbType.NVarChar).Value = TextBox1.Text;
SqlDataReader reader = command.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
connection.Close();
}
I am trying to use connected model to search a user's data in a table but the GridView is always, never fills with data.
You parameter is acting as a string in your query because of single quotes you have include around the parameter. That is the reason it is not able to identify the parameter. Try this:-
string query = "select * from aspnet_Users where userName LIKE #UserName";
Then add it as parameter like this:-
command.Parameters.Add("#MyName",SqlDBType.NVarChar,40).Value ="%" + TextBox1.Text + "%";
You can populate gridview using SqlDataAdapter, your code look like this
string query = "select * from aspnet_Users where userName like '%#UserName%'";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#UserName", TextBox1.Text);
cmd.Connection = conn;
SqlDataAdapter dap = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dap.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
How can I get the ID against the selected value of a DropDownList which is bound with DB?
Then how can I insert this ID into another table?
To get ID code
string query = "Select ID From Table-1 Where Name=" + DropDwonList.SelectedValue;
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
string getId = dr[0].ToString();
DropDownList Binding Code
string query = "Select ID, Name from Table-1";
SqlConnection con = new SqlConnection(conStr);
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
da.Fill(dt);
DropDwonList.DataSource = dt;
DropDwonList.DataTextField = "Name";
DropDwonList.DataValueField = "ID";
DropDwonList.DataBind();
DropDwonList.Items.Insert(0, new ListItem("--Select Name--"));
1) string Id = DropDwonList.SelectedValue;
2) To insert into another table just use a query:
string Id = DropDwonList.SelectedValue;
using (SqlConnection sql = new SqlConnection("Your connection string"))
{
SqlCommand cmd = new SqlCommand();
string query = #"INSERT INTO TABLE2(Column1)
VALUES(" + Id + ")";
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Connection = sql;
sql.Open();
cmd.ExecuteNonQuery();
sql.Close();
}
You should do it this way because you always ensure that you are closing a connection after using it.