C# drop downlist values not insert - c#

i have written a code to load the data to drop down list, as i written it was loaded, but while trying to insert the value of drop down list, (i mean selectedItem.text) it will not insert, instead if thtat selectedIndex=0 alone has been inserted. please correct me.
//Load the name to Drop down list
public void name()
{
DropDownList1.Items.Clear();
ListItem i = new ListItem();
i.Text = "-Select-";
DropDownList1.Items.Add(i);
DropDownList1.SelectedIndex = 0;
Conhr.Open();
string s;
s = "select EmployeeName from tbl_EmploeeDetails where SiteName='" + Label5.Text + "' ";
SqlCommand cd = new SqlCommand(s, Conhr);
SqlDataReader dr;
dr = cd.ExecuteReader();
while (dr.Read())
{
ListItem m= new ListItem();
m.Text = dr["EmployeeName"].ToString().Trim();
DropDownList1.Items.Add(m);
}
dr.Close();
Conhr.Close();
}
//trying to insert the data for drop down list
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
string a;
a = "insert into tbl_KKSUser(EName,Uname,Password)values(#en,#un,#pas)";
SqlCommand cm = new SqlCommand(a, con);
SqlParameter paramName;
paramName = new SqlParameter("#en", SqlDbType.VarChar, 25);
paramName.Value = DropDownList1.SelectedItem.Text;
cm.Parameters.Add(paramName);
cm.ExecuteNonQuery();
con.close
}
answer will be like this in data base
1 -Select- dsad AGEAcwBkAGY=
2 -Select- da AGEAZA==

Every time we are working with DropDownlist the best approach is selectedvalue,
Try to use:
Set the DataSource to the reader and execute DataBind()
conn.Open();
SqlDataReader MyDataSet = cmd.ExecuteReader();
ddlClassList.DataSource = MyDataSet;
ddlClassList.DataTextField = "Field1";
ddlClassList.DataValueField = "Field2";
ddlClassList.DataBind();
MyDataSet.Close();
conn.Close();

Related

Data does not exist for row/column when selectindexchange on Dropdownlist when clicked on dropdownlist.item.insert as empty position on dropdownlist

When I'm choosing additional (empty) position on Dropdownlist created by DropDownList.Item.Insert whole application is terminated.
if (!Page.IsPostBack)
{
DropDownList4.Items.Add(new ListItem("", ""));
DropDownList4.AppendDataBoundItems = true;
String strConnString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Projects\projects.accdb";
String strQuery = "select * from projects";
OleDbConnection con = new OleDbConnection(strConnString); ;
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
DropDownList4.DataSource = cmd.ExecuteReader();
DropDownList4.DataTextField = "Project_name";
DropDownList4.DataValueField = "ID";
DropDownList4.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
protected void DropDownList4_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Projects\projects.accdb";
string strQuery = "select * from projects where" + " ID = #ID";
OleDbConnection con = new OleDbConnection(strConnString);
OleDbCommand cmd = new OleDbCommand();
cmd.Parameters.AddWithValue("#ID", DropDownList4.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
OleDbDataReader myreader;
try
{
con.Open();
myreader = cmd.ExecuteReader();
myreader.Read();
TextBox12.Text = myreader["Project_name"].ToString();
TextBox2.Text = myreader["Owner"].ToString();
myreader.Close();
}
finally
{
con.Close();
}
}
As I'm thinking the reason is that the empty value does not exist in DB (but it is just created every time on Page_load by DropDownList4.Items.Add(new ListItem("", ""))). How to exclude from checking in DB first empty position on DropDownList?
Edited:
...
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
DropDownList4.DataSource = cmd.ExecuteReader();
if (DropDownList4.SelectedItem.Value == null || DropDownList4.SelectedItem == null)
{
}
DropDownList4.DataTextField = "Project_name";
DropDownList4.DataValueField = "ID";
DropDownList4.DataBind();
}
Still does not working
Edited:
string selected = DropDownList4.SelectedItem.Text;
if (string.IsNullOrEmpty(selected))
{
}
Now - It's working :)
You need (and want to) add the blank dropdown row AFTER you fill the dropdown.
So, say we have this markup:
<asp:DropDownList ID="DropDownList1" runat="server"
Height="26px" Width="207px" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
DataValueField="ID"
DataTextField="HotelName"
>
</asp:DropDownList>
And I DO suggest that you put the DataValue/Text settings in the control - really no need or advantage to putting that code in code behind.
And we don't need (or want) to re-load or re-insert the extra blank dropdown choice each time - so load the dropdown ONLY one time (the PostBack = false in page load as you attempted is correct).
So, we will select a hotel, and then pull that ONE database row for additional information - shove into a few text boxes as your code example does.
I suggest this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string strSQL =
"SELECT ID, HotelName FROM tblHotels ORDER BY HotelName";
OleDbCommand cmdSQL = new OleDbCommand(strSQL);
DropDownList1.DataSource = MyRstP(cmdSQL);
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("- Select.. -", "0"));
}
}
DataTable MyRstP(OleDbCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (OleDbConnection conn = new OleDbConnection(Properties.Settings.Default.AccessDB))
{
cmdSQL.Connection = conn;
using (cmdSQL)
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string HotelPK = DropDownList1.SelectedItem.Value as string;
string strSQL = "SELECT * FROM tblHotels where ID = #ID";
OleDbCommand cmdSQL = new OleDbCommand(strSQL);
cmdSQL.Parameters.Add("#ID", OleDbType.Integer).Value = HotelPK;
DataTable rstData = MyRstP(cmdSQL);
if (rstData.Rows.Count > 0)
{
DataRow OneRow = rstData.Rows[0];
TextBox1.Text = OneRow["HotelName"].ToString();
txtTaxRate.Text = OneRow["HotelTax"].ToString();
}
}
We also assume and have AutoPostBack = true for the drop list to fire each time we change it.

population of texboxes when combobox selected item is changed

Hello all I am trying to populate some textboxes automatically when I select an item from a combobox dropdown list using Microsoft sql server with a usercontrol form. I have written the codes below, however I am getting the items in the combox dropdown list but when I select an item in the combobox dropdown list, nothing happens in the text boxes. the values are in a table called competitors. the columns are Institution, Region, FirstName, LastName and I want the values to display in the respective textboxes when I select the combox dropdown. I seek your assistance in solving this problem. thanks in advance
private void RabbitCare_Load(object sender, EventArgs e)
{
CBoxParishDdlist.Items.Clear();
SqlConnection connect = new SqlConnection(#"Data Source=ITSPECIALIST\SQLPROJECTS;Initial Catalog=EXPRORESULTS;Integrated Security=True ");
connect.Open();
SqlCommand cmd = connect.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select ParishName FROM Competitors WHERE CompetitiveEventName = 'Care and Management of Bees'";
cmd.ExecuteNonQuery();
DataTable dat = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter(cmd);
SDA.Fill(dat);
foreach (DataRow DAR in dat.Rows)
{
CBoxParishDdlist.Items.Add(DAR["ParishName"].ToString());
}
connect.Close();
}
private void CBoxParishDdlist_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection connect = new SqlConnection(#"Data Source=ITSPECIALIST\SQLPROJECTS;Initial Catalog=EXPRORESULTS;Integrated Security=True ");
connect.Open();
cmd = new SqlCommand("SELECT * FROM Competitors WHERE ParishName = '" + CBoxParishDdlist.Text + "'", connect);
cmd.ExecuteNonQuery();
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
string Institution = (string)dr["Institution"].ToString();
TxtBoxInstitution.Text = Institution;
string Region = (string)dr["Region"].ToString();
TxtBoxRegion.Text = Region;
string FirstName = (string)dr["FirstName"].ToString();
TxtBoxFname.Text = FirstName;
string LastName = (string)dr["LastName"].ToString();
TxtBoxLname.Text = LastName;
}
connect.Close();
I think this will solve your problem.
TxtBoxInstitution.Text = comboBoxName.SelectedItem.ToString();

Updating data from combobox C#

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";
}
}

C# Add value to a texbox based on the Combobox selection

We have selected a value from a combobox and need the related information in the textbox.
The following code does not work for the same.
private void itemcode_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = (string)itemcode.SelectedItem;
SqlConnection conn3 = new SqlConnection(connString);
conn3.Open();
//For Redundency Checking Code of Supplier id.
string iname = "select Itemname from Items where Itemcode='" +
itemcode.SelectedItem.ToString() + "'";
SqlCommand cmdRedun1 = new SqlCommand(iname, conn3);
SqlDataReader dr1 = cmdRedun1.ExecuteReader();
dr1.Read();
itemname.Text = dr1["Itemname"].ToString();
dr1.Close();
}
First Check your Item Value Of Combo box , and then create your query with StringFormat
for example :
string iname = String.Format("select Itemname from Items where Itemcode='{0}'",
itemcode.SelectedItem.ToString()) ;
//-- then please check out below code :
SqlConnection SqlConn = new SqlConnection(this.ConnectionString);
SqlConn.Open();
SqlCommand SqlCmd = new SqlCommand(" Your Select....", SqlConn);
SqlCmd.CommandType = CommandType.Text;
SqlDataReader r = SqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
//----need this
while (r.Read())
itemname.Text = string.IsNullOrEmpty(r["Itemname"].ToString()) ?
string.Empty : r["Itemname"].ToString();
r.Close();
if (SqlConn.State != ConnectionState.Closed)
SqlConn.Close();
You can try ExecuteScalar instead of SqlDataReader.

Get value of combobox2 from combobox1

I got 2 comboboxes on my form(in the form load event). First combobox gets a value from a select statement once the form loads. I want to use that value in my second combobox. Here is my code:
1ste Combobox = cbDelivery
OracleConnection conn = new OracleConnection();
conn.ConnectionString = "User Id=christob;Password=CHRISTOB;Host=poseidon;Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0;Port=1522;Sid=GLODCD";
conn.Open();
string query;
query = "select distinct dd.delivery_bay_code from dc_delivery dd, dc_grv dg where delivery_complete_datetime is null and dd.dc_delivery_id_no = dg.dc_delivery_id_no and dd.delivery_announce_datetime is null";
OracleCommand cmd = new OracleCommand(query, conn);
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cbDelivery.Items.Add(dr["delivery_bay_code"]);
}
dr.Close();
conn.Close();
2de Combobox = cbOrderNo
This combobox is in:
private void cbDelivery_SelectedIndexChanged(object sender, EventArgs
e)
so as soon as I select a value from 1ste combobox my 2nd combobox query must populate the 2nd combobox. See code:
OracleConnection conn = new OracleConnection();
conn.ConnectionString = "User Id=christob;Password=CHRISTOB;Host=poseidon;Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0;Port=1522;Sid=GLODCD";
conn.Open();
string query1;
query1 = "select distinct dg.order_no from dc_delivery dd, dc_grv dg where delivery_complete_datetime is null and dd.dc_delivery_id_no = dg.dc_delivery_id_no and dd.delivery_announce_datetime is null and dd.delivery_bay_code = " + cbDelivery.Text;
OracleCommand cmd1 = new OracleCommand(query1, conn);
OracleDataReader dr1 = cmd1.ExecuteReader();
while (dr1.Read())
{
cbOderNo.Items.Add(dr1["order_no"]);
}
dr1.Close();
conn.Close();
Note I'm using cbDelivery combobox in my second Select query.
Problem is:
As soon as I select a value from my first combobox the second gives an exception ""ORA-00904: "BAY1": Invalid Identifier.
Please help me sort this out or suggest a different method.
Thanks in Advance.
May be your query using some keyword of sql or oracle as column name or at some invalid place. in such cases this type of errors are possible. I am not sure about this solution. but atleast we can try once. so that we can make it sure if its correct or not?
FIXED!! This is how i did it:
private void populateDeliveryBayCodes()
{
conn.Open();
string query;
query = "select distinct dd.delivery_bay_code from dc_delivery dd, dc_grv dg where dd.delivery_complete_datetime is null and dd.dc_delivery_id_no = dg.dc_delivery_id_no and dd.delivery_announce_datetime is null";
OracleCommand cmd = new OracleCommand(query, conn);
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cbDelivery.Items.Add(dr["delivery_bay_code"]);
}
dr.Close();
conn.Close();
}
private void populateOrderNumbers()
{
conn.Open();
string query;
query = "select distinct dg.order_no from dc_delivery dd, dc_grv dg where dd.delivery_complete_datetime is null and dd.dc_delivery_id_no = dg.dc_delivery_id_no and dd.delivery_announce_datetime is null and dd.delivery_bay_code ='" + cbDelivery.Text + "' order by order_no";
OracleCommand cmd = new OracleCommand(query, conn);
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cbOderNo.Items.Add(dr["order_no"]);
}
dr.Close();
conn.Close();
}
and
private void frmBuiltPallet_Load(object sender, EventArgs e)
{
populateDeliveryBayCodes();
{
private void cbDelivery_SelectedIndexChanged(object sender, EventArgs e)
{
populateOrderNumbers();
}

Categories