error on loading Sql value to dropdownlist - c#

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.

Related

ComboBox SelectedItem Not Changing

Edit: I am using window forms
So, I want to change a value of NumericUpDown if the selected value in combo box changes.
I placed a data table items with the columns ID, itemName, itemPrice and Stock and set the DisplayMember property to itemName.
I used this code:
cmb.DisplayMember = "itemName";
cmb.DataSource = items;
Then to get the whole row of the selected item I used
DataRow dataRow = ((DataRowView)cmbItems.SelectedItem).Row;
The problem is that in the UI, the combo box's selected item does not changes no matter what I do but the value of the selected item changes.
Like this.
I first thought that my unit is just lagging but its not. How do I fix this?
You can try this code to check if the combobox will get the selected item when you make your option.
dbConn.Open();// this allows you to edit the database
string sql = "Select * from database1";
SqlCommand dbComm = new SqlCommand(sql, dbConn);
SqlDataAdapter dbAdapter = new SqlDataAdapter(dbComm);
DataTable dt = new DataTable();
dbAdapter.Fill(dt);
cmbDescription.DataSource = dt;
cmbDescription.DisplayMember = "itemName";
cmbDescription.ValueMember = "Enter the column name here";
cmbDescription.Text = "";
cmbDescription.Items.Add(dt);
cdbConn.Close(); //close connection to save all your inputs,calculations to the database
I found out that my code is very confusing and the system seem to be having problems while executing, I've rewritten the whole code for this window form and it is working now.

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

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.

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;

How do I select Combobox value in DataGridView

I've 3 columns in DataGridView.
TextType
Combobox
TextType
I've bind Combobox of Datagridview like this:
BindingSource bindingSourceUnit = new BindingSource();
bindingSourceUnit.DataSource = datatableObject;
ColumnUnit.DataSource = bindingSourceUnit;
ColumnUnit.ValueMember = "id";
ColumnUnit.DisplayMember = "title";
This is showing all items in each row of the ComboBox second column.
Now I'm fetching data from a database and I want to display it in the DataGridView.
cmd = new OleDbCommand("SELECT * FROM Detail WHERE lr_id = #id", con);
cmd.Parameters.AddWithValue("#id", ID);
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
DataGridViewRow row = (DataGridViewRow)dgItem.Rows[0].Clone();
row.Cells[dgItem.Columns["ColumnQty"].Index].Value = reader["qty"];
row.Cells[dgItem.Columns["ColumnUnit"].Index].Value = reader["unit"];
row.Cells[dgItem.Columns["ColumnDesc"].Index].Value = reader["detail"];
dgItem.Rows.Add(row);
}
}
In the while loop, "ColumnUnit" is my ComboboxType field. It's not allowing me to pre-select the value.
How can I set the value for this column?
Are you using the Ajax combo box control or the standard check box list control?
In any case you need to tell the control which combo value should be selected, so you will have to do a check to see what the value is coming back from your database call and then search for that in the combo box list of values and when you find the correct value set the "selected" property to true
Try
row.Cells[dgItem.Columns["ColumnUnit"].Index].Selected = row.Cells[dgItem.Columns["ColumnUnit"].Index].Value == reader["unit"] ? true : false;
Try casting the cell into a DataGridViewComboBoxCell and you should be able to change the value that way.
var tempCombo = (DataGridViewComboBoxCell)drNew.Cells[0].Value;
A solution (perhaps not the best one):
private void dataGridView1_DefaultValuesNeeded(object sender,
System.Windows.Forms.DataGridViewRowEventArgs e)
{
e.Row.Cells["ColumnUnit"].Value = ... ; // set default value here
}

problem updating dropdownlist

I have a problem while updating changing the item in dropdownlist.
I have a dropdownlist which is populated in code behind file.
Here is the code:
departmentComm = new SqlCommand("SELECT DepartmentID, Department FROM Departments", conn);
conn.Open();
reader = departmentComm.ExecuteReader();
// Populate the list of categories
departmentList.DataSource = reader;
departmentList.DataValueField = "DepartmentID";
departmentList.DataTextField = "Department";
departmentList.DataBind();
// Close the reader
reader.Close();
I select one value from this list and saves it in my employee table. Now let's suppose I want to update this value in employee table.
Now my question is, how can I pull this value in dropdownlist and show it?
If you just van to get the selected department id:
departmentList.SelectedValue
gives you the id
If you embedded the dropdown in a datagrid you will need to update the database using a DataAdapter and call its Update method.
If you need more specifics you need to give more details.

Categories

Resources