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.
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;
I would like to know how can I display fixed data, based on the cascading dropdown list the user chooses? For example, I have 3 dropdown lists, on the last dropdown list if the user chooses "Yes", textbox will display "Position is approved" and if the user chooses "No", textbox will display "Position not approved". This is my code. I don't know what else to, please help.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillPackage();
}
}
private void FillPackage()
{
string strConn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT TopID, ToPackage FROM TableTop1";
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddl1.DataSource = objDs.Tables[0];
ddl1.DataTextField = "ToPackage";
ddl1.DataValueField = "TopID";
ddl1.DataBind();
ddl1.Items.Insert(0, "--Select--");
}
else
{
lblMsg.Text = "No Package found";
}
}
private void FillPurpose(int TopID)
{
string strConn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT PurposeID, Purpose FROM TablePurpose1 WHERE TopID =#TopID";
cmd.Parameters.AddWithValue("#TopID", TopID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddl2.DataSource = objDs.Tables[0];
ddl2.DataTextField = "Purpose";
ddl2.DataValueField = "PurposeID";
ddl2.DataBind();
ddl2.Items.Insert(0, "--Select--");
}
else
{
lblMsg.Text = "Please consult with focal person";
}
}
private void FillReason(int PurposeID)
{
string strConn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT ReasonID, Reason FROM TableReason1 WHERE PurposeID =#PurposeID";
cmd.Parameters.AddWithValue("#PurposeID", PurposeID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddl3.DataSource = objDs.Tables[0];
ddl3.DataTextField = "Reason";
ddl3.DataValueField = "ReasonID";
ddl3.DataBind();
ddl3.Items.Insert(0, "--Select--");
}
else
{
lblMsg.Text = "Please consult with focal person";
}
}
Since you have a Page_Load method in your snippet I'll consider your are using asp.net web forms. If that is the case you just have to handle the event emitted by the DropDownList component when it is changed.
I'm your c# code you should create a method to handle the event of an item being selected in your DropDownList, something like this:
protected void ItemSelected(object sender, EventArgs e)
{
if (ddl3.SelectedItem.Value == "Yes")
{
// Change text box text
}
}
And then you just have to hook your event handler to the component:
<asp:DropDownList ID="ddl3" runat="server" AutoPostBack="True"
onselectedindexchanged="ItemSelected">
</asp:DropDownList>
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.
i am C#.net Windows Form developer .
i am using FastReport.net . but have some error .
this is my code :
DataSet ds = new DataSet();
SqlConnection cnn = new SqlConnection("MyCnnStr");
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "select * from test";
cmd.CommandType = CommandType.Text;
SqlDataAdapter dap = new SqlDataAdapter(cmd);
dap.Fill(ds, "ds");
report1.RegisterData(ds.Tables[0],"ds");
report1.GetDataSource("ds").Enabled = true;
report1.Load("Untitled.frx");
report1.Show();
but my error :
what is my wrong ?
If name, tel and fax is names of tables, then you can try to write following:
DataSet ds = new DataSet();
SqlConnection cnn = new SqlConnection("MyCnnStr");
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "select * from test";
cmd.CommandType = CommandType.Text;
SqlDataAdapter dap = new SqlDataAdapter(cmd);
dap.Fill(ds, "ds");
report1.RegisterData(ds.Tables[0],"ds");
report1.GetDataSource("ds").Enabled = true;
report1.GetDataSource("name").Enabled = true; // add this part
report1.GetDataSource("tel").Enabled = true; //
report1.GetDataSource("fax").Enabled = true; //
report1.Load("Untitled.frx");
report1.Show();
Also you can try delete connections in Designer mode.
CS0103 may appear if you casually print symbol from other keyboard layout.
For example: E (English), Е (Russian), Ε (Greek).
How can i get the value of company_name from Comp table and store it on a comboBox?
here is my initial code on getting the values from Database and store it on a combobox:
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
comboBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString());
it point out to da.fill(ds) and says "Could not locate entry in sysdatabases for database 'select company_name from JO'. No entry found with that name. Make sure that the name is entered correctly."
hope for your reply thanks!
Use datareader it is much simpler \
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand(Sql, conn);
SqlDataReader DR = cmd.ExecuteReader();
while (DR.Read())
{
combobox1.Items.Add(DR[0]);
}
If you set up your connection string to be something of this sort:
string SqlConnectionString = "Data Source=[SERVER];Initial Catalog=[DATABASE];"
Then using that set up, you can set your string 'Sql' as:
string Sql = "select company_name from dbo.Comp";
This could be a possible set up you could use to read out the values.
using (SqlConnection saConn = new SqlConnection(this.ConnectionString))
{
saConn.Open();
string query = "select DBName from dbo.Company";
SqlCommand cmd = new SqlCommand(query, saConn);
using (SqlDataReader saReader = cmd.ExecuteReader())
{
while (saReader.Read())
{
string name = saReader.GetString(0);
combobox1.Add(name);
}
}
saConn.Close();
}
I would like to introduce you a very simple way to SQL data into a combobox as:
first you have a create a SQL table,
in C# platform drop a combobox and go to its property,
in the property menu click on "DataSource"
specify the database and table to load into combobox,
Note, the combobox name and table's row should be the same.
{
SqlConnection con =new SqlConnection("Data Source=Server_Name;Initial Catalog=Database_Name;integrated security=true");
SqlCommand cmd;
SqlDataReader dr;
private void CashMemoForm_Load(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("Select Column_Name From Table_Name", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
comboBox1.Items.Add(dr[0]).ToString();
}
}
}
Have you ever tried Entity Framework for database access and dto creation?
Change your line to cmd.CommandType = CommandType.Text; instead of cmd.CommandType = CommandType.StoredProcedure;
Try this
string Sql = "select Company_ID,company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
comboBox1.DataSource = ds.Tables[0];
comboBox1.DataTextField = "company_name";
comboBox1.DataValueField = "Company_ID";
comboBox1.DataBind();
comboBox1.Items.Insert(0, new ListItem("--Select--", "0"));
}
There is no use of for loop. you just need to check that whether the dataset contains rows or not.
string Sql = "select Company_ID,company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
comboBox1.DataSource = ds.Tables[0];
comboBox1.DataTextField = "company_name";
comboBox1.DataValueField = "Company_ID";
comboBox1.DataBind();
comboBox1.Items.Insert(0, new ListItem("Select", "0"));
}
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
comboBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString());
public System.Data.DataTable EmployeeViewAll()
{
DataTable dtbl = new DataTable();
try
{
// Here it shuld be your database Connection String
string connectionString = "Server = .; database = HKS; Integrated Security = true";
using (SqlConnection sqlCon = new System.Data.SqlClient.SqlConnection(connectionString))
{
SqlDataAdapter SqlDa = new SqlDataAdapter("employeeViewAll", sqlCon);
SqlDa.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlDa.Fill(dtbl);
}
return dtbl;
}
catch (Exception)
{
throw;
}
}
public void ComboFill()
{
DataTable dt = new DataTable();
eSP SP = new eSP();
d = SP.EmployeeViewAll();
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "department";
comboBox1.ValueMember = "empName";
}