3Layer C# asp.net: insert dropdownlist selected text and value - c#

I have a 3 Layer asp.net c# code. My BL:
public DataTable ddl()
{
base.Link();
string Query = "SELECT [nam], [idZone] FROM [zones] ORDER BY idZone";
DataTable Output_Q = base.SelectDataText(Query);
base.UnLink();
return Output_Q;
}
public void insert()
{
base.Link();
string Query = "INSERT INTO students (fnam, lnam, cod, idZone) VALUES ( '{0}', '{1}', '{2}', {3} )";
Query = string.Format(Query, fnam, lnam, cod, idZone);
base.commanddatatext(Query);
base.UnLink();
My Code:
page_load:
BL_students_new F = new BL_students_new();
DropDownList1.Items.Clear();
DropDownList1.DataSource = F.ddl();
DropDownList1.DataTextField = "nam";
DropDownList1.DataValueField = "idZone";
DropDownList1.DataBind();
btn_insert:
BL_students_new F = new BL_students_new();
F.fnam = TextBox1.Text.Trim();
F.lnam = TextBox2.Text.Trim();
F.cod = TextBox3.Text.Trim();
F.idZone = Convert.ToInt32(DropDownList1.SelectedItem.Value);
F.insert();
it saves every things but dropdownlist value. note that my ddl has text and int value and i need the value to be saved. but it fails. (My DA is OK too.)

From your comment above:
populating ddl is in page_load and inserting is in btn_insert
Page_Load happens before btn_Insert. This happens every time the page is requested, regardless of whether it's a "post back" or not. (After all, the page has to load into a usable state before it can even know the nature of the HTTP request.)
So what's happening is the following:
Bind the DropDownList options
Show the page to the user
User selects an option and submits
Re-bind the DropDownList options, losing whatever the user selected
Insert to database
A simple way to address this in WebForms is to wrap your DropDownList binding logic in a condition on IsPostBack. Something like this:
// in Page_Load:
if (!IsPostBack)
{
BL_students_new F = new BL_students_new();
DropDownList1.Items.Clear();
DropDownList1.DataSource = F.ddl();
DropDownList1.DataTextField = "nam";
DropDownList1.DataValueField = "idZone";
DropDownList1.DataBind();
}
That way you're only populating the DropDownList when the page is initially requested, not when the user is submitting the form.

Related

Binding the values in a dataset to a dropdown list

I have a dropdown list. I am getting data from oracle data base as a dataset I want to fill the dropdown list with dataset values(data text field and data value field). Data coming from the database as normal but I cant bind the values with my drop down list. "ds" is the dataset.
ddlDepartment.DataValueField = ds. Tables[0].Rows[0]["DEPARTMENT"].ToString();
ddlDepartment.DataTextField = ds. Tables[0].Rows[0]["DEPARTMENT_NAME"].ToString();
I think you might be grasping this wrong.
The dropdown combo has a simple setting that allows you to "set" WHAT values from the datasource will be used from the data table you "feed" the drop down list.
So, you can have this markup:
<asp:DropDownList ID="DropDownList1" runat="server"
Height="26px" Width="207px"
DataValueField="ID"
DataTextField="HotelName"
>
</asp:DropDownList>
So, you can set the two columns used - they are NOT for feeding data to the dropodown.
You can also set the above two columns in code - but LITTLE need exists to do that.
eg:
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "HotelName";
ONCE you set the above, you are now free to query the database, load up say a datatalbe, and then assign that "table" to the Dropdown list.
You do it this way:
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL = "SELECT ID,HotelName, City FROM tblHotels ORDER BY HotelName";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
DropDownList1.DataSource = rstData;
DropDownList1.DataBind();
// add one blank row selection.
DropDownList1.Items.Insert(0, new ListItem("- Select.. -", "0"));
}
}
So, note how the data table has 3 columns, but WHICH of the 3 do you want to use fo for the dropdown? You have two columns - typical the "ID" or "PK" value, and then the 2nd column is a text description.
Now, I am using the SqlProvider (for sql server). You have to replace SqlCommand with the OracleSQLcommand and also the connection. But the data table, and code that fills the dropdown list reamins the same as per above - regardless of what data provider you are using.
So those two settings (DataValueField, DataTextField) are NOT to be feed data, but are ONLY to set which columns to use from the data table. My example had 3 columns, but there could be 20 columns in that table - so those two settings determine which two columns to use. And often you might have a simple drop down to select a color or some such - and thus you ONLY need one column. In that case, set both Value/Text field to the one same column.
I was able to fill the dataset as follows at the page load
`private void filldepartment()
{
UserClass obj = new UserClass();
DataSet ds2 = new DataSet();
ds2.Merge(obj.departments());
ddlDepartment.DataSource = ds2.Tables[0];
ddlDepartment.DataTextField = "DEPARTMENT_NAME";
ddlDepartment.DataValueField = "DEPARTMENT_ID";
ddlDepartment.DataBind();
}`
and then find the values as follows
ddlDepartment.DataSource = ds;
ddlDepartment.DataBind();
Adjusted version of your code, removing unnecessary operations:
private void FillDepartmentDropDown()
{
UserClass obj = new UserClass();
var dt = obj.GetDepartments();
ddlDepartment.DataTextField = "DEPARTMENT_NAME";
ddlDepartment.DataValueField = "DEPARTMENT_ID";
ddlDepartment.DataSource = dt;
ddlDepartment.DataBind();
}
And then GetDepartments might look like:
public DataTable GetDepartments(){
using var da = new OracleDataAdapter(
"SELECT department_id, department_name FROM departments ORDER BY NLSSORT(department_name, 'NLS_SORT=GENERIC_M')",
_connstr
);
var dt = new DataTable();
da.Fill(dt);
}

error on loading Sql value to dropdownlist

I know that it sounds wrong. Is It possible to get the SQL value on the dropdown list anyway, so that one of the ListItem in dropdownlist is similar to SQL.
here is my code:
private void ReviewButtonPinsDetails()
{
con.Open();
cmd = new SqlCommand(#"SELECT quo_ProdCategory,quo_ProdType
,quo_JobDesc,quo_PrintProcess
,quo_File,quo_Finishing
,quo_Quantity
FROM JobQuotations1
WHERE TransactionID = #id
AND TransactionNum = #Num", con);
cmd.Parameters.AddWithValue("#id", GridView1.SelectedRow.Cells[2].Text);
cmd.Parameters.AddWithValue("#Num", GridView1.SelectedRow.Cells[4].Text);
rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
ddlProducts.Text = rdr["quo_ProductCategory"].ToString();
ddlProdName.Text = rdr["quo_ProdType"].ToString();
txtJobDesc.Text = rdr["quo_JobDesc"].ToString();
ddlPrintProc.Text = rdr["quo_PrintProcess"].ToString();
lblFileName.Text = rdr["quo_File"].ToString();
txtFinishing.Text = rdr["quo_Finishing"].ToString();
txtQty.Text = rdr["quo_Quantity"].ToString();
}
}
con.Close();
lblFileStatus.Text = "Previous File";
}
When the customer wanted to review His/Her order and select the row on grid view It suppose to restore the value of The textboxes and dropdownlist.
I don't quite understand the framework that you are working in but have you considered using the functionality offered by the INotifyPropertyChangedinterface.
Which will allow you to use the PropertyChangedEventHandler object.
Bind the textbox in the view to a property in your model.
You could then create some properties in the class that will hold the data for the text boxes and dropdowns and ensure that when a new property is set the
PropertyChangedEventHandler object you have created will handle updating the property in the view.
First bind your dropdownlist before Sql Value assign to it.
For example:
bindProducts(ddlProducts);
ddlProducts.SelectedValue = rdr["quo_ProductCategory"].ToString();
bindProducts(ddl as DropDownList) is the method for bind the product list to dropdownlist.

Dropdown list to show all values

I have been working on asp.net. I have a registration form with grid view.
The grid view contains the id of dropdownlist(ddl).
when i select the grid view ,all values have to be shown in appropriate fields in registration form.
For ddl, from the ddl id value in grid view ,appropriate dropdown list text is shown in dropdownlist.
THE PROBLEM COMES HERE, dropdown list showing only the appropriate value and AGAIN IT CANNOT BE CLICKED AND POPULATED FOR UPDATE BUTTON
enter image description here.
cmd.CommandText = "SELECT * FROM COMPANY WHERE COMPANYID='" + dbCompany + "'";
txtTextBox1.Text = newcmpid;
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
ddlCompanyName.DataSource = dt;
ddlCompanyName.DataTextField = "COMPANYNAME";
ddlCompanyName.DataValueField = "COMPANYID";
ddlCompanyName.DataBind();
HOW TO POPULATE THE DROPDOWNLIST WITH ALL ELEMENTS BY THE SAME TIME HIGHLIGHTING THE APPROPRIATE VALUE
To achive selection just use:
ddlCompanyName.Items.FindByValue(dbCompany).Selected = true;
But You should also notice that you SQL query is dangorous. It allows to create SQL inject attack. Instead of concatenating it you should SQL params.
So the full code could be like this:
cmd.CommandText = "SELECT * FROM COMPANY WHERE COMPANYID=#ID;";
cmd.Parameters.Add("#ID", SqlDbType.Int);
cmd.Parameters["#ID"].Value = dbCompany;
txtTextBox1.Text = newcmpid;
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
ddlCompanyName.DataSource = dt;
ddlCompanyName.DataTextField = "COMPANYNAME";
ddlCompanyName.DataValueField = "COMPANYID";
ddlCompanyName.DataBind();
ddlCompanyName.Items.FindByValue(dbCompany).Selected = true;

c# drop down selected text

I'm trying get text of the selected drop down item
My drop down list is filled of db data
ad.Fill(dt);
drop1.DataSource = dt;
drop1.DataTextField = "zodys";
drop1.DataValueField = "zodys";
drop1.DataBind();
for example: word1, word2, word3, ...
All this is working fine, but when I try get text of the selected item I always get same text (text of the 1 item)
txtZip.Text = drop1.SelectedItem.Text;
I can almost guarantee your problem is that you're defining the above within Page_Load()? You need to only do this if you're not posting back, like so:
if(!IsPostBack)
{
ad.Fill(dt);
drop1.DataSource = dt;
drop1.DataTextField = "zodys";
drop1.DataValueField = "zodys";
drop1.DataBind();
}
This ensures that the value is not being reset each time prior to checking the SelectedItem.
I assume that you're databinding the dropdown also on postbacks in page_load. You should check for IsPostBack.
if(!IsPostBack)
{
ad.Fill(dt);
drop1.DataSource = dt;
drop1.DataTextField = "zodys";
drop1.DataValueField = "zodys";
drop1.DataBind();
}

Combobox Value Loading Problem

Using C# & MySQL
When i select a particular value from the combobox then i clicked the button, the corresponding value should display in the other textbox
code
protected void Button1_Click(object sender, EventArgs e)
{
cmd2 = new OdbcCommand("Select name from users where username = '" + combobox1.Text + "' ", con);
dr1 = cmd2.ExecuteReader();
while (dr1.Read())
{
textbox1.Text = dr1.GetString(0);
}
dr1.Close();
}
The Above Code is working, but nothing displaying in Textbox1, there is the problem only in the query, I changed the query like Select name from users where username = '005'
Output is displaying in the textbox1, but when i used combobox value it is not displaying.
I also tried:
combobox1.text, combobox1.selectedvalue, combobox1.selecteditem, combobox1.selectedindex
Combobox Filling Code
cmd2 = new OdbcCommand("Select username from users, con);
ada2 = new OdbcDataAdapter(cmd2);
ada2.Fill(data2);
combobox1.DataValueField = "username";
combobox1.DataSource = data2;
combobox1.DataBind();
Username values like 201, 202, 203....,
Why is the query executing while using the combobox value....
Need Query Help
if you are using winform controls, please use below code
comboBox1.DataSource = list;
comboBox1.ValueMember = "Name";
to get value from combobox use comboBox1.SelectedValue[It will return object type]
comboBox1.Items[comboBox1.SelectedIndex].Text should give you what you want.
wrap your combo box's filling code in
if (!Page.IsPostBack) {}
It should be filled only when the page is loaded the first time and not on subsequent postbacks otherwise it will reset the binding everytime the page is posted back.
you should use combobox1.SelectedItem.Text for the desired result.

Categories

Resources