I using below code but it's not showing name in textbox.\
private void AllotLeaves_Load(object sender, EventArgs e)
{
display();
}
private void display()
{
SqlConnection conn = new SqlConnection(#"Data Source=.......");
conn.Open();
SqlDataAdapter ad = new SqlDataAdapter("select *from Emp_Details", conn);
DataSet ds = new DataSet();
ad.Fill(ds, "Emp_Details");
cballotid.DataSource = ds.Tables["Emp_Details"].DefaultView;
cballotid.DisplayMember = "ID";
cballotid.ValueMember = "ID";
}
private void cballotid_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=......");
conn.Open();
SqlCommand command = new SqlCommand("select Name from Emp_Details where ID=#ID", conn);
command.Parameters.AddWithValue("#ID", cballotid.Text);
Object temp = command.ExecuteScalar(); // this returns the first value of the select statement.
if (temp != null)
txtallotname.Text = temp.ToString();
conn.Close();
}
Try this
cballotid.DisplayMember = "Name";
cballotid.ValueMember = "ID";
cballotid.BindingContext = this.BindingContext;
Reference: ListControl.DisplayMember Property
You have to change this
cballotid.DisplayMember = "ID";
cballotid.ValueMember = "ID";
to
cballotid.DisplayMember = "name of field youd like to display";
cballotid.ValueMember = "ID";
Change this line as below:-
command.Parameters.AddWithValue("#ID", cballotid.SelectedValue);
Related
I m been working on a project in which i m facing an issue
I m having two drop down list which are Select category (ddlcategory) and select subcategory (ddlsubcategory) here are they
When I'm saving the data i m getting the ID saved into my database instead of category name and subcategory name Here is my database values :
Here is my back code i have implemented :
String constr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\PROJECT SEM6\Online Tours and Travels\App_Data\ToursandTravels.mdf;Integrated Security=True;User Instance=True";
string query = "";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindCategoryDropdown();
}
}
protected void btnpreviewwebsite_Click1(object sender, EventArgs e)
{
Response.Redirect("http://localhost:50550/Online Tours and Travels/index.aspx");
}
protected void btnlogout_Click(object sender, EventArgs e)
{
Session.Abandon();
Session.Clear();
Response.Redirect("http://localhost:50550/Online Tours and Travels/Admin Panel/LoginForm.aspx");
}
protected void BindCategoryDropdown()
{
//conenction path for database
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("select * from category", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddlcategory.DataSource = ds;
ddlcategory.DataTextField = "Cat_name";
ddlcategory.DataValueField = "Cat_id";
ddlcategory.DataBind();
ddlcategory.Items.Insert(0, new ListItem("--Select--", "0"));
ddlsubcategory.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void ddlcategory_SelectedIndexChanged(object sender, EventArgs e)
{
int categoryid = Convert.ToInt32(ddlcategory.SelectedValue);
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("select * from subcategory where catid=" + categoryid, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddlsubcategory.DataSource = ds;
ddlsubcategory.DataTextField = "subcatname";
ddlsubcategory.DataValueField = "subcatid";
ddlsubcategory.DataBind();
ddlsubcategory.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void btnsave_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constr);
String pathName1 = "~/packageimages/" + Path.GetFileName(fileuploadpic1.PostedFile.FileName);
String pathName2 = "~/packageimages/" + Path.GetFileName(fileuploadpic2.PostedFile.FileName);
String pathName3 = "~/packageimages/" + Path.GetFileName(fileuploadpic3.PostedFile.FileName);
query =
"insert into package(packname,catid,categoryname,subcatname,packageprice,pic1,pic2,pic3,detail) values('"+txtpackagename.Text+"','"+txtcategoryid.Text+"','"+ddlcategory.Text+"','"+ddlsubcategory.Text+"','"+txtpackageprice.Text+"','"+pathName1+"','"+pathName2+"','"+pathName3+"','"+txtdetails.Text+"') ";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
fileuploadpic1.SaveAs(Server.MapPath("~/packageimages/" + fileuploadpic1.FileName));
fileuploadpic2.SaveAs(Server.MapPath("~/packageimages/" + fileuploadpic2.FileName));
fileuploadpic2.SaveAs(Server.MapPath("~/packageimages/" + fileuploadpic3.FileName));
txtpackagename.Text = "";
txtcategoryid.Text = "";
txtpackageprice.Text = "";
txtdetails.Text = "";
string message = "Package Added !!";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
Please do help ! Thank You
answering your question - you need to use
ddlcategory.SelectedItem.Text not ddlcategory.Text
But as suggested, first do learn about query parameters
for example here
And about using statement for example here
The name of a Control gets generated by aspnet itself. Depending where in the control tree a Control is located, it could become something like this:
ctl00$ContentPlaceHolder1$ctl00$TextBox1
But if you really want to get the name, you can use UniqueID.
string controlName = TextBox1.UniqueID;
What i am trying to do is when a user selects a company from a comboBox then clicks the button the different text boxes are supposed to show the different data from the database.
This is what i have but it doesnt seem to work.
Any suggestions?
private void Edit_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(str))
{
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter("SELECT * FROM Companies", con);
DataTable dt = new DataTable();
adapt.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Name";
}
}
private void button3_Click(object sender, EventArgs e)
{
String company = comboBox1.SelectedItem.ToString();
String check = #"SELECT * FROM Companies WHERE Name=#name";
using (SqlConnection con = new SqlConnection(str))
using (SqlCommand cmd = new SqlCommand(check, con))
{
con.Open();
cmd.Parameters.Add("#name", SqlDbType.VarChar).Value = company;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
textBox1.Text = (reader["Name"].ToString());
textBox2.Text = (reader["PhNo"].ToString());
textBox3.Text = (reader["Email"].ToString());
textBox4.Text = (reader["Acc"].ToString());
textBox5.Text = (reader["Address"].ToString());
textBox6.Text = (reader["Suburb"].ToString());
textBox7.Text = (reader["PostCode"].ToString());
textBox8.Text = (reader["State"].ToString());
}
}
}
Update: the output of comboBox1.SelectedItem.ToString(); is System.Data.DataRowView so it seems to not be registering what the selected item is. How do i resolve this?
When the DataSource of your combo box is a DataTable, then the object in SelectedItem is of type DataRowView.
So to get a field, you can cast selected item to DataRowView and extract the field value this way:
var name = ((DataRowView)comboBox1.SelectedItem)["Name"].ToString();
In fact ((DataRowView)comboBox1.SelectedItem)["FieldName"] is of type object and you should cast the field to the desired type.
Try this
String check = "SELECT * FROM Companies WHERE Name=#name";
using (SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=ABCD;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand(check, con))
{
con.Open();
cmd.Parameters.Add("#name", SqlDbType.VarChar).Value = comboBox1.SelectedItem.ToString();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
textBox1.Text = reader["Name"].ToString();
textBox2.Text = reader["PhNo"].ToString();
textBox3.Text = reader["Email"].ToString();
textBox4.Text = reader["Acc"].ToString();
textBox5.Text = reader["Address"].ToString();
textBox6.Text = reader["Suburb"].ToString();
textBox7.Text = reader["PostCode"].ToString();
textBox8.Text = reader["State"].ToString();
}
}
Make sure your connectionstring is proper. Also Have you checked value of comboBox1.SelectedItem.ToString() and same is present in db?
If you are populating drop down from database then refer this: System.Data.DataRowView in DropDownList
Updated:
private void ComboBoxBinding()
{
using (SqlConnection con = new SqlConnection(str))
{
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter("SELECT Name,Id FROM Companies", con);
DataTable dt = new DataTable();
adapt.Fill(dt);
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Id";
comboBox1.DataSource = dt;
comboBox1.DataBind();
}
}
You can call this function either in page load or in class constructor.
Try the code below it will work,the thing that you are missing is you are not setting the ValueMember property of your combo box.
Suggestion :
1.Debug your code and make sure that your query is correct and your able to getting the value right values from data source.
2.Make sure that your columns names in your database table are exactly same as you are setting in your combo box display member and value member
using (SqlConnection connection = new SqlConnection("Data Source=.;Initial Catalog=\"Student Extended\";Integrated Security=True"))
{
SqlCommand command = new SqlCommand
{
Connection = connection,
CommandText = "SELECT DepartmentId,DepartmentName FROM dbo.TblDepartment"
};
SqlDataAdapter adpater = new SqlDataAdapter(command);
DataTable table = new DataTable();
adpater.Fill(table);
if (txtStdDeptName != null)
{
txtStdDeptName.DataSource = table;
txtStdDeptName.DisplayMember = "DepartmentName";
txtStdDeptName.ValueMember = "DepartmentId";
}
}
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
I have two related comboboxes, combobox1 populate the items of combobox2. In combobox1 selectIndexChanged event I have this code but i have error Unknown column 'System.Data.DataRowView' in 'where clause'.
I tried to put this code in the SelectionChangeCommitted at first selection, it populate the right items, but my second selection i have error in comboBox2.Items.Clear(); states Items collection cannot be modified when the DataSource property is set. :( what to do.?
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string sql;
if (comboBox1.SelectedIndex >= 0)
{
comboBox2.Items.Clear();
MySqlConnection conn = new MySqlConnection(sqlString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
sql = "SELECT brgyname,idbrgy from barangay where idmun=" + comboBox1.SelectedValue;
adapter.SelectCommand = new MySqlCommand(sql, conn);
DataTable cbBrgy = new DataTable();
adapter.Fill(cbBrgy);
comboBox2.DataSource = cbBrgy;
comboBox2.DisplayMember = "brgyname";
comboBox2.ValueMember = "idbrgy";
}
}
Here's how i populate combobox1
private void cbMun()
{
MySqlConnection conn = new MySqlConnection(sqlString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = new MySqlCommand("SELECT munname,idmun from municipality", conn);
DataTable cbMun = new DataTable();
adapter.Fill(cbMun);
comboBox1.DataSource = cbMun;
comboBox1.DisplayMember = "munname";
comboBox1.ValueMember = "idmun";
}
while cbMun function is filling the combobox it will call combobox selected index change event directly , so to work around this define bool value comboisloading = true and modify your code such like below :
private void cbMun()
{
MySqlConnection conn = new MySqlConnection(sqlString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = new MySqlCommand("SELECT munname,idmun from municipality", conn);
DataTable cbMun = new DataTable();
adapter.Fill(cbMun);
comboBox1.DataSource = cbMun;
comboBox1.DisplayMember = "munname";
comboBox1.ValueMember = "idmun";
comboisloading = false;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboisloading)
return;
string sql;
if (comboBox1.SelectedIndex >= 0)
{
comboBox2.Items.Clear();
MySqlConnection conn = new MySqlConnection(sqlString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
sql = "SELECT brgyname,idbrgy from barangay where idmun=" + comboBox1.SelectedValue;
adapter.SelectCommand = new MySqlCommand(sql, conn);
DataTable cbBrgy = new DataTable();
adapter.Fill(cbBrgy);
comboBox2.DataSource = cbBrgy;
comboBox2.DisplayMember = "brgyname";
comboBox2.ValueMember = "idbrgy";
}
}
I just placed my code in comboBox1_SelectionChangeCommitted not in comboBox1_SelectedIndexChanged event since comboBox1.SelectedValue is still not generated not unless the user committed its changes to the items. Also my Items collection cannot be modified when the DataSource property is set error from comboBox2.Items.Clear(); i just deleted this line of code. I still clears and replace my combobox2 items properly. Hmm.. Since i used to clear comboboxes in vb..I wonder.
private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
string sql;
MySqlConnection conn = new MySqlConnection(sqlString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
sql = "SELECT brgyname,idbrgy from barangay where idmun=" + comboBox1.SelectedValue;
adapter.SelectCommand = new MySqlCommand(sql, conn);
DataTable cbBrgy = new DataTable();
adapter.Fill(cbBrgy);
comboBox2.DataSource = cbBrgy;
comboBox2.DisplayMember = "brgyname";
comboBox2.ValueMember = "idbrgy";
}
I've been working on this one since someone teaches me to use gridview to display my search result.
My problem is, I can't even make it work, when I click or hit the search button, nothing happen. I have:
-1 textbox for last name
-2 dropdownlist for the province and city
-and a search(trigger)button
Here's what I've done so far:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_province ORDER BY PROVINCE_NAME ASC", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlProvince.DataSource = dt;
ddlProvince.DataTextField = "PROVINCE_NAME";
ddlProvince.DataValueField = "PROVINCE_CODE";
ddlProvince.DataBind();
}
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_city WHERE PROVINCE_CODE =#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#pcode";
param.Value = ddlProvince;
comm.Parameters.Add(param);
}
ddlCity.DataSource = dt;
ddlCity.DataTextField = "CITY_NAME";
ddlCity.DataValueField = "CITY_CODE";
ddlCity.DataBind();
}
private void BindGridView(string field)
{
DataTable dt = new DataTable();
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
try
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_accredited_providers WHERE DOCTOR_CODE =#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#pcode";
param.Value = ddlProvince;
comm.Parameters.Add(param);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
}
// NO RECORDS FOUND
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
BindGridView(txtName.Text.Trim());
}
}
I'm new to this, please assist me. Thanks!
You are not using the field string variable that you are passing to BindGridView and you are mismanaging your SQL parameters (adding the same parameter twice and assigning a DropDown object as a parameter value).
You are adding the same parameter twice.
To fix this, remove this line: comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
You are not using the field variable.
To fix this, change this line
param.Value = ddlProvince; // Note: You are assigning a dropdown OBJECT as the value here!
to
param.Value = field;
in your BindGridView function.