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;
Related
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.
Searching via the InqID is working properly but when I give the code to Search with InqName it gives me an error (All connections are given Properly I guess) Thanks..
ERROR DETAILS
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: No value given for one or more required parameters.
private void btnSearch_Click(object sender, EventArgs e)
{
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqID=" +txtInqID.Text, CON);
DS.Clear();
DA.Fill(DS);
dataGridView.DataSource = DS.Tables[0];
CON.Open();
DA.SelectCommand.ExecuteNonQuery();
CON.Close();
}
private void btnNameSearch_Click(object sender, EventArgs e)
{
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqName=" + txtInqName.Text, CON);
DS.Clear();
DA.Fill(DS);
dataGridView.DataSource = DS.Tables[0];
CON.Open();
DA.SelectCommand.ExecuteNonQuery();
CON.Close();
}
Most of the answers tell you that you should use parameters and that is good.
They also tell you that it would be correct if you included single quotes around it, which is incorrect. Adding single quotes is NOT a solution and would only work for some values (well many but not all) and is wide open to SQL injection attack.
There is only one way of doing it correct and that is to use parameters. With OleDb the parameters are NOT named but positional. With access however you can use named parameters by prefixing them with #.
private void btnSearch_Click(object sender, EventArgs e)
{
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqID=#ID", CON);
DA.SelectCommand.Parameters.Add("#ID", OleDbType.VarChar).Value = txtInqID.Text;
DS.Clear();
DA.Fill(DS);
dataGridView.DataSource = null;
dataGridView.DataSource = DS.Tables[0];
}
private void btnNameSearch_Click(object sender, EventArgs e)
{
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqName=#name", CON);
DA.SelectCommand.Parameters.Add("#name", OleDbType.VarChar).Value = txtInqName.Text;
DS.Clear();
DA.Fill(DS);
dataGridView.DataSource = null;
dataGridView.DataSource = DS.Tables[0];
}
PS: You are using DataSet and DataAdapter in a weird way, but that is acceptable and works.
You are not specifying the search string parameter, you should add quotes as follows:
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqName='" + txtInqName.Text + "'", CON);
However, constructing the query string as string is not an effective and readable way, the good practice is to use OleDbParameters as follows:
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqName=?", CON);
DA.SelectCommand.Parameters.AddWithValue("?", txtInqName.Text);
You are missing quotes that enclose your txtInqID.Text and InqName.Text values in your query:
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqID = '" + txtInqID.Text + "'", CON);
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqName = '" + txtInqName.Text + "'", CON);
Also building dynamically your query string like that is a very bad practice. Consider using command parameters instead:
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqID = ?", CON);
DA.SelectCommand.Parameters.Add("InqID").Value = txtInqID.Text;
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqName = ?" , CON);
DA.SelectCommand.Parameters.Add("InqName").Value = txtInqName.Text;
You need to surround the value of Name in quotes but it would be better to use Parameterized Sql.
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqName=#Name " , CON);
DS.Clear();
DA.SelectCommand.Parameters.AddWithValue("#Name",txtInqName.Text);
DA.Fill(DS);
dataGridView.DataSource = DS.Tables[0];
Also you don't need below code as data is already selected using DataAdapter
CON.Open();
DA.SelectCommand.ExecuteNonQuery();
CON.Close();
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.
Data type mismatch in criteria expression.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: Data type mismatch in criteria expression.
Source Error:
Line 77: int Subject_ID = Convert.ToInt32(DropDown_SubjectName.SelectedValue);
Line 78: OleDbCommand cmd = new OleDbCommand("select * from Assignment_Details where Subject_ID = " + Subject_ID, con);
Line 79: cmd.ExecuteNonQuery();
Line 80: cmd.CommandType = CommandType.Text;
Line 81:
public partial class WebForm2 : System.Web.UI.Page
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E://Project//VirtualClassRoomDB//VirtualClassroomDB.accdb");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindSubjectdropdown();
}
}
protected void BindSubjectdropdown()
{
//conenction path for database
con.Open();
OleDbCommand cmd = new OleDbCommand("select * from Subject_Details", con);
cmd.CommandType = CommandType.Text;
try
{
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
}
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DropDown_SubjectName.DataSource = ds;
DropDown_SubjectName.DataTextField = "Subject_Name";
DropDown_SubjectName.DataValueField = "Subject_ID";
DropDown_SubjectName.DataBind();
DropDown_SubjectName.Items.Insert(0, new ListItem("--Select--", "0"));
DropDown_AssignmentName.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void Button_Ass_Add_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand("insert into Assignment_Details(Assignment_Name,Assignment_Description,Subject_ID,Upload_by,Assignment_Path) values('" + TextBox_AssignementName.Text + "','" + TextBox_AssignmentDescription.Text + "','" + DropDown_Subject.SelectedValue + "','Maths','" + FileUpload_Assignment.FileName + "')", con);
cmd.CommandType = CommandType.Text;
}
protected void DropDown_SubjectName_SelectedIndexChanged(object sender, EventArgs e)
{
con.Open();
int Subject_ID = Convert.ToInt32(DropDown_SubjectName.SelectedValue);
OleDbCommand cmd = new OleDbCommand("select * from Assignment_Details where Subject_ID = " + Subject_ID, con);
cmd.ExecuteNonQuery();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DropDown_AssignmentName.DataSource = ds;
DropDown_AssignmentName.DataTextField = "Assignment_Name";
DropDown_AssignmentName.DataValueField = "Assignment_ID";
DropDown_AssignmentName.DataBind();
DropDown_AssignmentName.Items.Insert(0, new ListItem("--Select--", "0"));
}
}
cmd.ExecuteNonQuery();
is not what you want. That is how you run an action query, not a select query. You also have this line too late:
cmd.CommandType = CommandType.Text;
it should appear before you execute the query.
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();