I have a datalist which contain product catagory with unique ID asign to every products in my catalog. However, when i checked 2 or more checkboxes, i will only get the latest data display next page, but not all the data displayed. Just 1 data displayed only. Is there any way i can do so that I can pass 3 different ID at a time and display on nxt page?
void GetCheckedBox()
{
foreach (DataListItem li in DataList1.Items)
{
//access the check checklist
HtmlInputCheckBox cb = li.FindControl("FavChkBox") as HtmlInputCheckBox;
if (cb != null && cb.Checked)
{
ArrayList Product = new ArrayList();
LblText.Text += " , ";
LblText.Text += cb.Value;
Product.Add(cb.Value);
string url = "CompareProducts.aspx?prodId=" + cb.Value.ToString();
Response.Redirect(url);
}
}
}
CompareProducts.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Product aProd = new Product();
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("SELECT * FROM Products WHERE Product_ID = #ProdID", con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
cmd.Parameters.AddWithValue("#ProdID", Page.Request.QueryString["ProdID"].ToString());
con.Open();
adp.Fill(ds, "Products");
cmd.ExecuteNonQuery();
con.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
DataList1.DataSource = ds;
DataList1.DataBind();
}
I'm not totally sure what you are saying, but based on your code I see in your ForEach loop you have a response.redirect, so in this case you will only redirect to a single ID querystring. You could switch your to use a session variable that holds a list of all the ID's the user selected.
foreach (DataListItem li in DataList1.Items)
{
//access the check checklist
HtmlInputCheckBox cb = li.FindControl("FavChkBox") as HtmlInputCheckBox;
if (cb != null && cb.Checked)
{
ArrayList Product = new ArrayList();
LblText.Text += " , ";
LblText.Text += cb.Value;
Product.Add(cb.Value);
}
Session.Add("SelectedProducts", Product);
string url = "CompareProducts.aspx?hasProducts=true;
Response.Redirect(url);
}
Then in your CompareProducts.aspx.cs on pageload if not postback check the querystring to decide if you should load the id's.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Page.Request.QueryString["hasProducts"].ToString() == "true")
{
ArrayList al = Session["SelectedProducts"] as ArrayList;
if (al == null)
throw new ApplicationException("A product list is required.");
if (al.Count < 1)
throw new ArgumentException("No products selected");
string inStatement = string.Empty;
foreach (var item in al)
{
inStatement += al.ToString() + ", ";
}
inStatement = inStatement.Substring(0, inStatement.Length - 2);
//Product aProd = new Product();
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("SELECT * FROM Products WHERE Product_ID in (" + inStatement + ")", con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
con.Open();
adp.Fill(ds, "Products");
cmd.ExecuteNonQuery();
con.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
DataList1.DataSource = ds;
DataList1.DataBind();
}
Related
When I use the scanner to scan the barcode,
the item will be add in the first row and when I scan the second barcode,
the item will no add in the datagridview but it just adds a row only.
My column in datagridview is productid, ProductName, Description, Stock, UOM, Price
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
DataGridViewRow newRow = new DataGridViewRow();
if (textBox1.Text.Length != 0)
{
conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=F:\Database\book1.mdf;Integrated Security=True;Connect Timeout=30");
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter("SELECT productid,ProductName,Description,Stock,UOM,Price from ProductTable where productId='" + textBox1.Text + "'", conn);
DataTable dt = new DataTable();
adp.Fill(dt);
foreach (DataRow item in dt.Rows)
{
int i = dataGridView1.RowCount -1;
dataGridView1.Rows.Insert(i);
dataGridView1.Rows.Add();
dataGridView1.Rows[i].Cells[0].Value = item[0].ToString();
dataGridView1.Rows[i].Cells[1].Value = item[1].ToString();
dataGridView1.Rows[i].Cells[2].Value = item[2].ToString();
dataGridView1.Rows[i].Cells[3].Value = item[3].ToString();
dataGridView1.Rows[i].Cells[4].Value = item[4].ToString();
dataGridView1.Rows[i].Cells[5].Value = item[5].ToString();
}
}
}
}
Page Screenshots:
https://ibb.co/pJ0fnx7
Your approach if your productid is a unique key as it should be, will always be returning only one result, I really dont see the need of the foreach statement here. Moreover every time you open a conn to the database you should be closing it.
My approach with this in mind would be a little different this would be
Public Class clsConn
{
Public List<Data> getSomething()
var SqlConn = new SqlConnection("your connection");
try
{
SqlConn.Open();
string sqlstring = "your sql sentence";
SqlCommand SqlCmd = new SqlCommand(sqlstring, SqlConn);
SqlDataReader reader = SqlCmd.ExecuteReader();
List<Data> dataList = new List<Data>();
if (reader.Read())
{
Data data = new Data();
data.productid = reader[0].ToString(); // this is just an example
dataList.Add(data);
}
return dataList;
}
catch (Exception ex)
{
MessageBox.Show("conexion to DB failed: " + ex.Message);
throw;
}
finally
{
SqlConn.Close();
}
}
}
}
And you should have a public data class that has all the properties you need like this for example
public class Data
{
public string productid { get; set; }
}
To use it, you have to work like this
List<Data> dbData = new List<Data>();
clsConn db = new clsConn();
dbData = db.getSomething();
//I ll leave the foreach but as I said this should be only one result
foreach (var item in DBData)
{
dataGridView1.Rows.Add(item.productid);
}
Your .Insert()-call does not provide the row to insert, and you do not handle the index returned from the Rows.Add()-call.
I have edited your code a bit so that it should work now.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode != Keys.Enter) || (textBox1.Text.Length == 0))
{
return;
}
conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=F:\Database\book1.mdf;Integrated Security=True;Connect Timeout=30");
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter("SELECT productid,ProductName,Description,Stock,UOM,Price from ProductTable where productId='" + textBox1.Text + "'", conn);
DataTable dt = new DataTable();
adp.Fill(dt);
foreach (DataRow item in dt.Rows)
{
int i = dataGridView1.Rows.Add();
DataGridViewRow row = dataGridView1.Rows[i];
row.Cells[0].Value = item[0].ToString();
row.Cells[1].Value = item[1].ToString();
row.Cells[2].Value = item[2].ToString();
row.Cells[3].Value = item[3].ToString();
row.Cells[4].Value = item[4].ToString();
row.Cells[5].Value = item[5].ToString();
}
}
And do not forget to close your database connection. Consider using the using-statement for this.
You should also check this: How to add a new row to datagridview programmatically
I want to put a combobox in my datagridview. I've tried differents ways (creating a var list<>, creating an arraylist, ect...) and none is working. The thing is my column already exist because of my select query that show my database in the datagridview. But the column is empty since in my database the column is fill with NULL value.
I have two choices : Creating a combobox and do an addcolumn, or if you know how to do it link my combobox to the already existing column. And obviously i need help creating my combobox.
Thank you !
My code :
public partial class Repair : Form
{
public Repair()
{
Main pp = new Main();
InitializeComponent();
this.label4.Text = pp.label3.Text;
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
SqlCommand command = maConnexion.CreateCommand();
SqlCommand command1 = maConnexion.CreateCommand();
if (Program.UserType == "admin")
{
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, RepairingTime FROM FailAndPass WHERE FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE FComponent IS NOT NULL";
}
else
{
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, RepairingTime FROM FailAndPass WHERE ReportingOperator IS NULL AND FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE ReportingOperator IS NULL AND FComponent IS NOT NULL";
}
SqlDataAdapter sda = new SqlDataAdapter(command);
SqlDataAdapter sda1 = new SqlDataAdapter(command1);
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
sda.Fill(dt);
sda1.Fill(dt1);
DataColumn dcIsDirty = new DataColumn("IsDirty", typeof(bool));
DataColumn dcIsDirty1 = new DataColumn("IsDirty", typeof(bool));
dcIsDirty.DefaultValue = false;
dcIsDirty1.DefaultValue = false;
dataGridView1.DataSource = dt;
dataGridView2.DataSource = dt1;
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "FaultCodeByOp";
combo.Name = "combo";
ArrayList list = new ArrayList();
list.Add("C-C");
list.Add("C-O");
combo.Items.AddRange(list.ToArray());
dataGridView1.Columns.Add(combo);
dt.Columns.Add(dcIsDirty);
dt1.Columns.Add(dcIsDirty1);
maConnexion.Close();
dataGridView1.Columns[6].Visible = false;
dataGridView2.Columns[3].Visible = false;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for(int i=0;i<4;i++)
{
dataGridView1.Columns[i].ReadOnly = true;
}
}
foreach (DataGridViewRow row in dataGridView2.Rows)
{
for(int i=0;i<3;i++)
{
dataGridView2.Columns[i].ReadOnly = true;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
Main ff = new Main();
ff.Show();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
string Var1 = textBox1.Text;
SqlCommand command = maConnexion.CreateCommand();
SqlCommand command1 = maConnexion.CreateCommand();
if (Program.UserType == "admin")
{
if (textBox1.Text != String.Empty)
{
//command.Parameters.AddWithValue("#BoardName", Var1 + "%");
//command.Parameters.AddWithValue("#Machine", Var1 + "%");
command.Parameters.AddWithValue("#SerialNum", Var1 + "%");
command1.Parameters.AddWithValue("#SerialNum", Var1 + "%");
//command.Parameters.AddWithValue("#FComponent", Var1 + "%");
//command.CommandText = "SELECT * FROM FailAndPass WHERE BoardName LIKE #BoardName OR Machine LIKE #Machine OR SerialNum LIKE #SerialNum OR FComponent LIKE #FComponent";
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, FaultCodeByOp, RepairingTime FROM FailAndPass WHERE SerialNum LIKE #SerialNum AND FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE SerialNum LIKE #SerialNum And FComponent IS NOT NULL";
}
}
else
{
if (textBox1.Text != String.Empty)
{
//command.Parameters.AddWithValue("#BoardName", Var1 + "%");
//command.Parameters.AddWithValue("#Machine", Var1 + "%");
command.Parameters.AddWithValue("#SerialNum", Var1 + "%");
command1.Parameters.AddWithValue("#SerialNum", Var1 + "%");
//command.Parameters.AddWithValue("#FComponent", Var1 + "%");
//command.CommandText = "SELECT * FROM FailOnly WHERE (BoardName LIKE #BoardName OR Machine LIKE #Machine OR SerialNum LIKE #SerialNum OR FComponent LIKE #FComponent) AND ReportingOperator IS NULL ";
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, FaultCodeByOp, RepairingTime FROM FailAndPass WHERE (SerialNum LIKE #SerialNum) AND ReportingOperator IS NULL AND FComponent IS NOT NULL ";
command1.CommandText = "SELECT DISTINCT Machine, BoardName, BoardNumber FROM FailAndPass WHERE (SerialNum LIKE #SerialNum) AND ReportingOperator IS NULL AND FComponent IS NOT NULL";
}
}
if (!string.IsNullOrWhiteSpace(textBox1.Text))
{
SqlDataAdapter sda = new SqlDataAdapter(command);
SqlDataAdapter sda1 = new SqlDataAdapter(command1);
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
sda.Fill(dt);
sda1.Fill(dt1);
DataColumn dcIsDirty = new DataColumn("IsDirty", typeof(bool));
DataColumn dcIsDirty1 = new DataColumn("IsDirty", typeof(bool));
dcIsDirty.DefaultValue = false;
dcIsDirty1.DefaultValue = false;
dt.Columns.Add(dcIsDirty);
dt1.Columns.Add(dcIsDirty1);
dataGridView1.DataSource = dt;
dataGridView2.DataSource = dt1;
maConnexion.Close();
dataGridView1.Columns[6].Visible = false;
dataGridView2.Columns[3].Visible = false;
}
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((row.Cells[6].Value != null) && (bool)row.Cells[6].Value)
{
SqlCommand command = maConnexion.CreateCommand();
command = new SqlCommand("update FailAndPass set FaultCodeByOp=#Fault, RepairingDate=#RD, RepairingTime = #RT, ReportingOperator=#RO WHERE SerialNum=#Serial", maConnexion);
command.Parameters.AddWithValue("#Fault", row.Cells[4].Value != null ? row.Cells[4].Value : DBNull.Value);
command.Parameters.AddWithValue("#RD", DateTime.Today.ToString("d"));
command.Parameters.AddWithValue("#RT", row.Cells[5].Value != null ? row.Cells[5].Value : DBNull.Value);
command.Parameters.AddWithValue("#RO", this.label4.Text);
command.Parameters.AddWithValue("#Serial", this.textBox1.Text);
command.ExecuteNonQuery();
}
}
maConnexion.Close();
this.Hide();
Repair rep = new Repair();
rep.Show();
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.IsCurrentRowDirty)
{
dataGridView1.Rows[e.RowIndex].Cells[6].Value = true;
}
}
}
private void ComboboxInDatagridview()
{
var dataGridView1 = new DataGridView();
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "FaultCodeByOp";
combo.Name = "combo";
dataGridView1.Columns.AddRange(new DataGridViewColumn[] { combo });
ArrayList list = new ArrayList() { "C-C", "C-O" };
var rowindex = dataGridView1.Rows.Add();
DataGridViewComboBoxCell cmbCell = (DataGridViewComboBoxCell)dataGridView1["combo", rowindex];
//Or
//var columnindex = 0;
//DataGridViewComboBoxCell cmbCell = (DataGridViewComboBoxCell)dataGridView1[columnindex, rowindex];
cmbCell.DataSource = list;
}
Anyone having other solutions ? I've tried something else :
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
ArrayList list1 = new ArrayList(); //{ "C-C", "C-O", "Absence composant", "Mauvaise valeur", "Mauvais sens", "Mauvais composant" };
list1.Add("C-C");
list1.Add("C-O");
combo.DataSource = list1;
combo.HeaderText = "FaultCodeByOp";
combo.DataPropertyName = "FaultCodeByOp";
dataGridView1.Columns.AddRange(combo);
didnt change anything.
I dont know what i've done, but it is not greyish anymore. Now it is white like other columns.... but it doesnt dropdown, nor show members of the list.
I have a checkListBox in my windows form application and binded with my database data with SQL. I populate a list of item according to what I select from my comboBox. If I select item 1 from my comboBox, it will display customers' name who is using this item. I want get customers' id according to what I check in my checkListBox.
Here is how I fill my comboBox
private void fill_comboBox()
{
myConn = new SqlConnection("Server = localhost; Initial Catalog= dbName; Trusted_Connection = True");
try
{
string query = "select itemId, itemName from item_detail";
SqlDataAdapter da = new SqlDataAdapter();
myConn.Open();
DataTable dt = new DataTable();
SqlCommand command = new SqlCommand(query, myConn);
SqlDataReader reader = command.ExecuteReader();
dt.Load(reader);
DataRow dr;
dr= dt.NewRow();
dr.ItemArray = new object[] { 0, "<----------Select an item-------> " };
dt.Rows.InsertAt(dr, 0);
itemComboBox.DataSource = dr;
itemComboBox.ValueMember = "itemId";
itemComboBox.DisplayMember = "itemName";
fill_customerCheckListBox();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here is how I fill my checkListBox
private void fill_customerCheckListBox()
{
myConn = new SqlConnection("Server = localhost; Initial Catalog= dbName; Trusted_Connection = True");
try
{
myConn.Open();
DataSet myDataSet = new DataSet();
myDataSet.CaseSensitive = true;
string commandString = "select fullName from[customer_detail] as cd LEFT JOIN[item_customer] as ic ON ic.customerId= cd.customerI WHERE ic.itemId= '" + itemCombBox.SelectedValue + "' ";
myCommand = new SqlCommand();
myCommand.Connection = myConn;
myCommand.CommandText = commandString;
SqlDataAdapter myDataAdapter = new SqlDataAdapter();
myDataAdapter.SelectCommand = myCommand;
myDataAdapter.TableMappings.Add("Table", "customer_detail");
myDataAdapter.Fill(myDataSet);
DataTable myDataTable = myDataSet.Tables[0];
customerCB.Items.Clear();
string s = "Select All Customer";
customer.Items.Add(s);
foreach (DataRow dataRow in myDataTable.Rows)
{
customerCB.Items.Add(dataRow["fullName"]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I have a praremter for loop that trying to loop through every checked item from my customerCB, but this isn't working. When I am in my debug mode, the code DataRow row = (itemChecked as DataRowView).Row; is causing an exception
Object reference is not set to an instance of an object.
I have no idea how to fix this. Help will be appreciated, thanks
string parameterList = "";
foreach (object itemChecked in customerCB.CheckedItems)
{
DataRow row = (itemChecked as DataRowView).Row;
parameterList += (parameterList.Length == 0) ? row[0].ToString() : ", " + row[0].ToString();
}
Try the Following way !!
foreach(object itemChecked in checkedListBox1.CheckedItems)
{
DataRowView castedItem = itemChecked as DataRowView;
string fullName= castedItem["fullName"];
}
(OR) You would need to cast or parse the items to their strongly typed equivalents, or use the System.Data.DataSetExtensions namespace to use the DataRowExtensions.Field method demonstrated below:
foreach (var item in checkedListBox1.CheckedItems)
{
var row = (itemChecked as DataRowView).Row;
int id = row.Field<int>("ID");
string name = row.Field<string>("fullName");
}
it seems than when you are populating your combobox your are entering dataRow["fullName"] therefore this cast DataRow row = (itemChecked as DataRowView).Row won't work as itemChecked only contains the value of fullName and not the row, try adding the dataRow instead.
I have two tables called facility and Facilitytype_lookup table with relationship with each other using fac_type column field. In the first drop down list I populate the data using fac_type field on facility table, and if the selected fac_type field value is selected, for example selecting LT, the fac_code belonging to that fac_type will be displayed on the second drop down list which is L.337 and L.338 like in the screenshots. The problem is I want the first dropdownlist names to be in full. For etc MR as Meeting Room, DR as discussion Room, LT for leture Theatre. That';s why I created another table called Facilitytype_lookup with the column field called fac_name. How do I make the first drop down list names to be in full names using column field fac_name??
public partial class MainMenu : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//string constr = ConfigurationManager.ConnectionStrings["serverConnectionString"].ToString(); // connection string
string constr = ConfigurationManager.ConnectionStrings["projectConnectionString"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("select distinct FAC_TYPE from FACILITY", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds); // fill dataset
ddlFacilityType.DataTextField = ds.Tables[0].Columns["FAC_TYPE"].ToString(); // text field name of table dispalyed in dropdown
// to retrive specific textfield name
ddlFacilityType.DataSource = ds.Tables[0]; //assigning datasource to the dropdownlist
ddlFacilityType.DataBind(); //binding dropdownlist
ddlFacilityType.Items.Insert(0, new ListItem(" Select type", "0"));
}
ddlFacility.Items.Insert(0, new ListItem(" Select room", "0"));
}
protected void ddlFacilityType_SelectedIndexChanged(object sender, EventArgs e)
{
//string constr = ConfigurationManager.ConnectionStrings["serverConnectionString"].ToString(); // connection string
string constr = ConfigurationManager.ConnectionStrings["projectConnectionString"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("select distinct FAC_CODE from FACILITY where FAC_TYPE='" + ddlFacilityType.SelectedValue.ToString() + "'", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds); // fill dataset
ddlFacility.DataTextField = ds.Tables[0].Columns["FAC_CODE"].ToString(); // text field name of table dispalyed in dropdown
// to retrive specific textfield name
ddlFacility.DataSource = ds.Tables[0]; //assigning datasource to the dropdownlist
ddlFacility.DataBind(); //binding dropdownlist
ddlFacility.Items.Insert(0, new ListItem(" Select room", "0"));
}
protected void ddlFacility_SelectedIndexChanged(object sender, EventArgs e)
{
Session["roomvalue"] = ddlFacility.SelectedValue;
if (ddlFacilityType.Text == "MR")
{
Response.Redirect("number1.aspx");
}
else if (ddlFacilityType.Text == "DR")
{
Response.Redirect("number1.aspx");
}
else
Response.Redirect("number2.aspx");
}
}
Edited, first dropdownlist will display fac_name values, but after choosing any option in first drop down list, second drop down list doesn't come out anything
public partial class MainMenu : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//string constr = ConfigurationManager.ConnectionStrings["serverConnectionString"].ToString(); // connection string
string constr = ConfigurationManager.ConnectionStrings["projectConnectionString"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("select distinct facility.FAC_TYPE, facilitytype_lookup.fac_name from FACILITY inner join facilitytype_lookup ON facility.fac_type=facilitytype_lookup.fac_type", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds); // fill dataset
ddlFacilityType.DataTextField = ds.Tables[0].Columns["FAC_name"].ToString(); // text field name of table dispalyed in dropdown
// to retrive specific textfield name
ddlFacilityType.DataSource = ds.Tables[0]; //assigning datasource to the dropdownlist
ddlFacilityType.DataBind(); //binding dropdownlist
ddlFacilityType.Items.Insert(0, new ListItem(" Select type", "0"));
}
ddlFacility.Items.Insert(0, new ListItem(" Select room", "0"));
}
protected void ddlFacilityType_SelectedIndexChanged(object sender, EventArgs e)
{
//string constr = ConfigurationManager.ConnectionStrings["serverConnectionString"].ToString(); // connection string
string constr = ConfigurationManager.ConnectionStrings["projectConnectionString"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("select distinct FAC_CODE from FACILITY where FAC_TYPE='" + ddlFacilityType.SelectedValue.ToString() + "'", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds); // fill dataset
ddlFacility.DataTextField = ds.Tables[0].Columns["FAC_CODE"].ToString(); // text field name of table dispalyed in dropdown
// to retrive specific textfield name
ddlFacility.DataSource = ds.Tables[0]; //assigning datasource to the dropdownlist
ddlFacility.DataBind(); //binding dropdownlist
ddlFacility.Items.Insert(0, new ListItem(" Select room", "0"));
}
protected void ddlFacility_SelectedIndexChanged(object sender, EventArgs e)
{
Session["roomvalue"] = ddlFacility.SelectedValue;
if (ddlFacilityType.Text == "MR")
{
Response.Redirect("number1.aspx");
}
else if (ddlFacilityType.Text == "CR")
{
Response.Redirect("number1.aspx");
}
else if (ddlFacilityType.Text == "DR")
{
Response.Redirect("number1.aspx");
}
else
Response.Redirect("number2.aspx");
}
}
I have a dynamically bind dropdownlist from which i want insert selected value in a table. But when I submit the form it is taking the very first value of dropdownlist not the selected value and inserts the first value of the dropdownlist.
Here is my code
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(connection.getConnection()))
{
string sqlGetClass = "select pk_classID,brachName+'-'+classYear as classInfo from tbl_studentClass";
SqlCommand cmdGetClass = new SqlCommand(sqlGetClass, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdGetClass);
DataSet ds = new DataSet();
da.Fill(ds);
ddlClass.DataSource = ds;
ddlClass.DataTextField = "classInfo";
ddlClass.DataValueField = "pk_classID";
ddlClass.DataBind();
ddlClass.Items.Insert(0, new ListItem("--SELECT--", ""));
conn.Close();
}
}
protected void btnStdRegisterSubmit_Click(object sender, EventArgs e)
{
string dateOfBirth = txtStdDOBYear.Text+"-"+ddlStdDOBMonth.SelectedValue + "-"+txtStdDOBDate.Text;
using (SqlConnection conn = new SqlConnection(connection.getConnection()))
{
string sqlInsertStd = "Insert into tbl_studentRegistration (firstName,surname,studentUsername,studentPassword,studentDOB,studentGender,studentMobile,class) values(#firstName,#surname,#studentUsername,#studentPassword,#studentDOB,#studentGender,#studentMobile,#class)";
conn.Open();
SqlCommand cmdInsertStd = new SqlCommand(sqlInsertStd, conn);
cmdInsertStd.Parameters.AddWithValue("#firstName", txtStdFirstName.Text);
cmdInsertStd.Parameters.AddWithValue("#surname", txtStdSurname.Text);
cmdInsertStd.Parameters.AddWithValue("#studentUsername", txtStdUsername.Text);
cmdInsertStd.Parameters.AddWithValue("#studentPassword", txtStdPassword.Text);
cmdInsertStd.Parameters.AddWithValue("#studentDOB", DateTime.Parse(dateOfBirth).ToString("yyyy-MM-dd"));
cmdInsertStd.Parameters.AddWithValue("#studentGender", ddlStdGender.SelectedValue.ToString());
cmdInsertStd.Parameters.AddWithValue("#studentMobile", txtStdMobile.Text);
cmdInsertStd.Parameters.AddWithValue("#class", ddlClass.SelectedValue);
cmdInsertStd.ExecuteNonQuery();
conn.Close();
txtStdFirstName.Text = "";
txtStdSurname.Text = "";
txtStdUsername.Text = "";
ddlClass.SelectedValue = "";
txtStdPassword.Text = "";
txtStdConfirmPassword.Text = "";
ddlStdDOBMonth.SelectedValue = "";
txtStdDOBDate.Text = "";
txtStdDOBYear.Text = "";
ddlStdGender.SelectedValue = "";
txtStdMobile.Text = "";
Response.Redirect("~/index.aspx");
}
}
Please help I am new to asp.net
Problem : You are adding the items into DropDownList for every Page request as your code added in Page_Load EventHandler. so the DropDownList always contain the first item as selectedItem even though you selected different item.
Solution: You need to append the items into DropDownList only when page is Loaded but not on every PostBack request.
You can use Page.IsPostBack to identify wether page request is PostBack request or not.
Try This:
if(!Page.IsPostBack)
{
using (SqlConnection conn = new SqlConnection(connection.getConnection()))
{
string sqlGetClass = "select pk_classID,brachName+'-'+classYear as
classInfo from tbl_studentClass";
SqlCommand cmdGetClass = new SqlCommand(sqlGetClass, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdGetClass);
DataSet ds = new DataSet();
da.Fill(ds);
ddlClass.DataSource = ds;
ddlClass.DataTextField = "classInfo";
ddlClass.DataValueField = "pk_classID";
ddlClass.DataBind();
ddlClass.Items.Insert(0, new ListItem("--SELECT--", ""));
conn.Close();
}
}
Page_Load executes every time the page posts back, such as when you click your submit button. You should put your using stateme3nt in a
conditional:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
using (SqlConnection conn = new SqlConnection(connection.getConnection()))
{
string sqlGetClass = "select pk_classID,brachName+'-'+classYear as classInfo from tbl_studentClass";
SqlCommand cmdGetClass = new SqlCommand(sqlGetClass, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdGetClass);
DataSet ds = new DataSet();
da.Fill(ds);
ddlClass.DataSource = ds;
ddlClass.DataTextField = "classInfo";
ddlClass.DataValueField = "pk_classID";
ddlClass.DataBind();
ddlClass.Items.Insert(0, new ListItem("--SELECT--", ""));
conn.Close();
}
}
}
So that your list is not repopulated every time you click your submiit button.
(you should consider putting the list population code in a separate method)