Populating a dropdownlist using a SQL Connection - c#

I have a DropdownList in asp.net form that needs populating through SQL. I'm using a ScriptManager in my Page_Load()and due to this dropdownList doesn't get populated. I need to use the ScriptManager since I'm using a AjaxCalendarExtender.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = dba.getNames();
ddNames.DataSource = ds.Tables["EMPLOYEE"].DefaultView;
ddNames.DataTextField = "Username";
ddNames.DataValueField = "Username";
ddNames.DataBind();
}
if (ScriptManager.GetCurrent(Page) == null)
{
Page.Form.Controls.AddAt(0, new ScriptManager());
}
}
getNames() function in DB_Access.cs
public DataSet getNames()
{
if (conn.State.ToString() == "Closed")
{
conn.Open();
}
SqlCommand newCmd = conn.CreateCommand();
newCmd.Connection = conn;
newCmd.CommandType = CommandType.Text;
newCmd.CommandText = "Select DISTINCT Username from dbo.EMPLOYEE";
SqlDataAdapter da = new SqlDataAdapter(newCmd);
DataSet ds = new DataSet();
da.Fill(ds, "EMPLOYEE");
conn.Close();
return ds;
}

I found the answer to be in the Script Manager in aspx page instead of Creating the it Dynamically in the Page Load event.
<asp:ScriptManager ID="ScriptManager1" runat="server" />

Related

Inserting multiple listitems of dropdownlist into multiple rows of the database

I am trying to insert multiple selected values of a asp.DropdownList into multiple rows of a database. I am using Silvio Montero bootstrap select CSS to acheive multiple selection.
I am using a foreach() loop to do it but only the first selected item is getting inserted into the database. The asp.DropdownList is populated from another database.
<asp:ListBox runat="server" CssClass="selectpicker form-control" multiple data-live-search="true" ID="DropDownList1" DataTextField="username" DataValueField="username" >
</asp:ListBox>
Here is the c# code for that -
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownList();
}
}
private void BindDropDownList()
{
using (SqlConnection con = new SqlConnection(CS))
using (SqlCommand cmd = new SqlCommand("SELECT DISTINCT [username], [email] FROM [Login]", con))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "username";
DropDownList1.DataValueField = "username";
DropDownList1.DataBind();
}
}
protected void sendbutton_Click(object sender, EventArgs e)
{
foreach (ListItem item in DropDownList1.Items)
{
if (item.Selected)
{
using (SqlConnection sqlcon = new SqlConnection(CS))
{
sqlcon.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = sqlcon;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO DB (schdlby, schdldate, schdltime, sub, event, participants ) values (#schdlby, #schdldate, #schdltime, #sub, #event, #participants)";
cmd.Parameters.AddWithValue("#schdlby", Page.User.Identity.Name.ToString());
cmd.Parameters.AddWithValue("#schdldate", cl.SelectedDate.ToShortDateString());
cmd.Parameters.AddWithValue("#sub", txtsub.Text);
cmd.Parameters.AddWithValue("#schdltime", schdltime.Text.Trim());
cmd.Parameters.AddWithValue("#event", txtevent.Text);
cmd.Parameters.AddWithValue("#parti", item.Value.ToString());
cmd.ExecuteNonQuery();
// Code to send automated SMTP mail to each dropdown selection
}
}
}
}
Response.Redirect("Second.aspx");
}
Edit: I just found that it works in asp:CheckBoxList but does not work when asp:ListBox is used

How to keep Dropdown value same after refresh the page

I am using three dropdowns, in first dropdown i bind data from sql. In second dropdown i also bind data from sql and the third dropdown is bind according to second dropdown so in second dropdown there is autopostback property true. I have one search button which fetch the result from database on click.
I want to keep all the Dropdownlist value same after my result show on the page. One thing i did is, at the time of button click i make the session and check it at page load when it is not null bind the dropdown value. Till this point it is working fine i am able to bind prevoius selected values.
This is in my master page and result are display in result page, which is using this masterpage.
aspx :
<asp:DropDownList ID="dd_category" runat="server" AutoPostBack="True"
onselectedindexchanged="dd_category_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="dd_subcategory" runat="server" ></asp:DropDownList>
<asp:Button ID="but_go" runat="server" Text="Go" onclick="but_go_Click"/>
page load :
if (!IsPostBack)
{
FillStates();
FillCategory();
}
if (Session["state"] != null)
{
dd_state.SelectedValue = (string) Session["state"];
}
aspx.cs :
private void FillStates()
{
SqlCommand cmd = new SqlCommand("sps_bindcountrystate", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#flag", 2);
cmd.Parameters.AddWithValue("#CountryID", 1);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
dd_state.DataSource = objDs.Tables[0];
dd_state.DataTextField = "s_name";
dd_state.DataValueField = "s_id";
dd_state.DataBind();
dd_state.Items.Insert(0, "Select State");
}
}
protected void dd_category_SelectedIndexChanged(object sender, EventArgs e)
{
int CategoryID = Convert.ToInt32(dd_category.SelectedValue);
FillSubCategory(CategoryID);
}
private void FillCategory()
{
SqlCommand cmd = new SqlCommand("sps_bindcategory", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#flag", 1);
cmd.Parameters.AddWithValue("#CategoryID", 0);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
dd_category.DataSource = objDs.Tables[0];
dd_category.DataTextField = "category_name";
dd_category.DataValueField = "category_id";
dd_category.DataBind();
dd_category.Items.Insert(0, "Select Category");
dd_subcategory.Items.Insert(0, "Select Sub-Category");
}
}
private void FillSubCategory(int CategoryID)
{
SqlCommand cmd = new SqlCommand("sps_bindcategory", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#flag", 2);
cmd.Parameters.AddWithValue("#CategoryID", CategoryID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
dd_subcategory.DataSource = objDs.Tables[0];
dd_subcategory.DataTextField = "subcategory_name";
dd_subcategory.DataValueField = "subcategory_id";
dd_subcategory.DataBind();
dd_subcategory.Items.Insert(0, "Select Sub-Category");
}
}
protected void but_go_Click(object sender, EventArgs e)
{
Session["state"] = dd_state.SelectedValue;
Session["category"] = dd_category.SelectedValue;
Session["subcategory"] = dd_subcategory.SelectedValue;
Response.Redirect("Results.aspx");
}
Now problem is when i again choose some different value in first dropdown and try to choose different value in second dropdown, the second dropdown is having postback so it refreshes page and according to session state it changes my first dropdown value back to prevoius one.
Tell me what to do so that new selected value does'nt change due to page refresh.

Dynamically Binded Dropdownlist always taking first value when get by ddl.SelectedValue

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)

Gridview display

I dont know what it is but i'm having all sorts of issues with this gridview. Below is the code but the issues is the grid is not displaying. Visibility is set to true and the query does return results. So I'm asking for another set of eyes to point out what went wrong here.
Thank you
protected void btnDisplay_Click(object sender, EventArgs e)
{
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\levels.mdb";
DataSet ds;
using (OleDbConnection myConnString = new OleDbConnection())
{
myConnString.ConnectionString = connString;
using (OleDbCommand selectCommand = new OleDbCommand())
{
selectCommand.CommandText = "select * from tblTest";
selectCommand.Connection = myConnString;
myConnString.Open();
using(OleDbDataAdapter da = new OleDbDataAdapter())
{
da.SelectCommand = selectCommand;
ds = new DataSet();
da.Fill(ds, "test");
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
}//end click event
and the gridview
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
or
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
data source should have been:
GridView1.DataSource = ds.Tables["test"];
GridView1.DataBind();

selecting index change of dropdownlist related prblm

i have a 3 tables: Section,Class and Student...now i want to loading the studentName on the dropdownlist based on selection Class with selecting section in dropdown list[Here Section Field,Class Field will b select by dropdownlist and StudentName also show in to the dropdownlist]
Here is my Table preview
SectionEnty
Id,SectionTitle,Capacity
ClassEntry
Id,ClassTitle,SectionId
StudentInfo
Id,FullName,ClassId,Section
it will b very helpful for me. If any one help me at this situation because i am all ready tried but its not working because of multiple index handling.
ASPX:
<asp:DropDownList ID="classdropdown" runat="server" OnSelectedIndexChanged="classdropdown_SelectedIndexChanged" AutoPostBack="true" />
<asp:DropDownList ID="sectiondropdown" runat="server" OnSelectedIndexChanged="sectiondropdown_SelectedIndexChanged" AutoPostBack="true" />
<asp:DropDownList ID="studentnamedropdown" runat="server" />
C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.LoadClassDropdown();
}
}
// set initial values
private void LoadClassDropdown()
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT Id,SectionTitle FROM SectionEnty", "your connection string"))
{
using (DataSet ds = new DataSet())
{
da.SelectCommand.Connection.Open();
da.Fill(ds);
da.SelectCommand.Connection.Close();
classdropdown.DataSource = ds;
classdropdown.DataValueField = "Id";
classdropdown.DataTextField = "SectionTitle";
classdropdown.DataBind();
}
}
}
protected void classdropdown_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT Id,ClassTitle FROM ClassEntry WHERE SectionId = #SectionId", "your connection string")
{
da.SelectCommand.Parameters.Add(new SqlParameter("#SectionId", sectiondropdown.SelectedValue));
using (DataSet ds = new DataSet())
{
da.SelectCommand.Connection.Open();
da.Fill(ds);
da.SelectCommand.Connection.Close();
sectiondropdown.DataSource = ds;
sectiondropdown.DataValueField = "Id";
sectiondropdown.DataTextField = "ClassTitle";
sectiondropdown.DataBind();
}
}
}
protected void sectiondropdown_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT Id,FullName FROM StudentInfo WHERE ClassId = #ClassId", "your connection string"))
{
da.SelectCommand.Parameters.Add(new SqlParameter("#ClassId", classdropdown.SelectedValue));
using (DataSet ds = new DataSet())
{
da.SelectCommand.Connection.Open();
da.Fill(ds);
da.SelectCommand.Connection.Close();
studentnamedropdown.DataSource = ds;
studentnamedropdown.DataValueField = "Id";
studentnamedropdown.DataTextField = "FullName";
studentnamedropdown.DataBind();
}
}
}
Now your studentnamedropdown contains the list for the selected class and section.
Any questions, let me know...

Categories