Dropdown list populated from database - asp.net

I have populated a dropdownlist from a database. Now on select of a particular item I want the data to come from the database and get displayed in a label, but, when I am selecting a particular item, the page gets loaded again and in the dropdownlist --SELECT-- comes again and not the value which I previously selected.
My code is-
aspx page-
https://stackoverflow.com/editing-help
codebehind-
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UI"]==null)
{
Response.Redirect("AdminLogin.aspx");
}
else
{
if (!IsPostBack)
{
AddVehicle vb = new AddVehicle();
DataSet tt = vb.populatedropdown();
DropDownList1.DataSource = tt;
DropDownList1.DataTextField = "DealerID";
DropDownList1.DataValueField = "DealerID";
DropDownList1.DataBind();
}
}
}

Related

Update the data in database in asp.net

I can successfully select the data I want to update to another page and populate my text boxes but if I set the selected values to my textbox and then try to update it wouldn't work and the same data is shown in database table.
However if I DO NOT set those values to my textboxes, then I can successfully update which is not what I am after.
I would like the user to see the data and record that s being updated
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
UserClassesDataContext db= new UserClassesDataContext();
var qr = from user in db.Users
where user.user_id == new Guid(Request.QueryString["user_id"])
select user;
foreach (var q in qr)
{
TextBox1.Text = q.user_name;
TextBox2.Text = q.password;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
UserClassesDataContext db = new UserClassesDataContext();
var qr = from user in db.Users
where user.user_id == new Guid(Request.QueryString["user_id"])
select user;
foreach (var q in qr)
{
q.user_name = TextBox1.Text;
q.password = TextBox2.Text;
}
db.SubmitChanges();
Response.Redirect("Default.aspx");
}
What am I doing wrong?
Thanks
The problem is, when you submit the button, the code inside Page_Load event is executing again.That means it is reading the data from your table and setting the value to textboxes(thus overwriting what user updated via the form ) and you are updating your record with this values (original values). So basically you are updating the rows with same values.
You can use the Page.IsPostBack property to determine whether the event is occurred by a postback(button click) or initial page load.
This should fix it.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// to do: read and set to textbox here.
}
}

unable to persist data on postback in dotnetnuke7

I have my website running on dotnetnuke 7.4, i have a checklistbox which i bind on the page load, and after selecting items from it, user clicks on the submit button, the selected items should save in database, however when i click on the submit button, checklistbox gets blank, i tried to enable ViewState at :
Web.config level
Page Level
Control Level
But all in vain, it still unbinds checklistbox because of which everything disappears, i tried the same in plain .net and it works like a charm.
Is there any specific settings in dotnetnuke to support viewstate, or is there any other better option to achieve this.
Here's my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Entities objEntities = new Entities();
List<Entities> obj = objEntities.GetList(2);
chkBox.DataSource = obj;
chkBox.DataTextField = "Name";
chkBox.DataValueField = "ID";
chkBox.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (ListItem item in chkBox.Items)
Response.Write(item.Text + "<br />");
}
There's the issue. Remove that (!IsPostBack) check in your page_load event. Have your code to be like below. Else, only at first page load you are binding the datasource to control which gets lost in postback.
protected void Page_Load(object sender, EventArgs e)
{
Entities objEntities = new Entities();
List<Entities> obj = objEntities.GetList(2);
chkBox.DataSource = obj;
chkBox.DataTextField = "Name";
chkBox.DataValueField = "ID";
chkBox.DataBind();
}
OR, to be more efficient; refactor your code to a method like below and store the data object in Session variable like
private void GetDataSource()
{
List<Entities> obj = null;
if(Session["data"] != null)
{
obj = Session["data"] as List<Entities>;
}
else
{
Entities objEntities = new Entities();
obj = objEntities.GetList(2);
}
chkBox.DataSource = obj;
chkBox.DataTextField = "Name";
chkBox.DataValueField = "ID";
chkBox.DataBind();
Session["data"] = obj;
}
Call the method in your Page_Load event like
protected void Page_Load(object sender, EventArgs e)
{
GetDataSource();
}

I need a DropDown value that is linked to another page

I have a DropDown List where I have brought the values from my Database using code-behind.
I have added a new value after reading data from source, called ".. Add new skill".
Now when user clicks on that item I need a small page (or rather a new page) to open to add the skills that are not mentioned in the DropDownList.
if (!IsPostBack)
{
SqlConnection myConn = new SqlConnection(#"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True");
SqlCommand myCmd = new SqlCommand(
"SELECT SkillName, SkillID FROM Skills", myConn);
myConn.Open();
SqlDataReader myReader = myCmd.ExecuteReader();
//Set up the data binding.
DropDownList1.DataSource = myReader;
DropDownList1.DataTextField = "SKillName";
DropDownList1.DataValueField = "SkillID";
DropDownList1.DataBind();
//Close the connection.
myConn.Close();
myReader.Close();
//Add the item at the first position.
DropDownList1.Items.Insert(0, "..Add New Skill");
}
This is my code-behind file.. How do I link that now?
You should use the SelectedIndexChanged event and SelectedValue property:
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(String.Compare(ddl.SelectedValue,"..Add New Skill",true)==0)
Response.Redirect("Add_New_Skill.aspx");
}
Add a SelectedIndexChanged event handler to that dropdown like this
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(ddl.SelectedIndex == 0)
Response.Redirect("Add_New_Skill.aspx");
}
If you want position of "...Add new skill" to be at last of the list
Use this
ddl.Items.Insert(ddl.Items.Count, "...Add New Skill");
Now to redirect to another page you should do this
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(ddl.SelectedIndex == ddl.Items.Count-1)
Response.Redirect("Add_New_Skill.aspx");
}
Set AutoPostBack to true. That way when the user changes an option, it will automatically post the page to the server.
Handle this SelectedIndexChanged event, and redirect to your add page there.
Take your user to a add page.
Add the details to the database.
Bring the user back to this page.
List will be reloaded from database, and you till get your value.
No special linking is required.
This is working
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindDropdownlist()
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string getvalue = DropDownList1.SelectedItem.Value;
if (getvalue == "..Add New Skill")
{
Response.Redirect("Default.apsx");
}
}
public void bindDropdownlist()
{
SqlDataAdapter dap = new SqlDataAdapter("select coloumn1,colum2 from table", con);
DataSet ds = new DataSet();
dap.Fill(ds);
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataTextField = "coloumn1";
DropDownList1.DataValueField = "colum2 ";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "..Add New Skill");
}
}
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
</div>

Fields not changing in Formview when moving Pagination

I have a formview that on page load makes a call to a sql server and retrieves 5 records which I want the formview to paginate though.
I have sucessfully connected to the db, filled a dataset, and returned data when the web page renders. The problem is that when I move to a new page, the data does not change in the databound field.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
conn = new SqlConnection(connstr);
ds = new DataSet();
da = new SqlDataAdapter("call to stored proc", conn);
try
{
conn.Open();
da.Fill(ds, "m");
FormView1.DataSource = ds;
FormView1.DataKeyNames = new string[] { "PropKey" };
FormView1.DataBind();
}
catch (Exception ex)
{
Result = ex.Message;
}
finally
{
conn.Close();
}
}
Next when the paginate buttons are clicked I have this:
protected void FormView1_PageIndexChanging1(object sender, FormViewPageEventArgs e)
{
FormView1.PageIndex = e.NewPageIndex;
}
Please help,
Thanks
You will need to bind the data to the FormView just after setting the new page index like below.
protected void FormView1_PageIndexChanging1(object sender, FormViewPageEventArgs e)
{
FormView1.PageIndex = e.NewPageIndex;
BindFormViewData();
}
This is required because the FormView only displays the data for the active record and does not store any other records from the datasource, so upon change of the page index, the datasource is required to be bound again. See: Paging in a FormView Web Server Control
From the above link:
If the FormView control is bound to a data source control, or to any
data structure that implements the ICollection interface (including
datasets), the control gets all the records from the data source,
displays the record for the current page, and discards the rest. When
the user moves to another page, the FormView control repeats the
process, displaying a different record.
Hope this helps.

How to programmatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource

I'm using XmlDataSource as the datasource for a dropdownlist.
Now I want to set the SelectedValue of the drop down when the page initially loads. I have tried the OnDataBound event of the drop down in which I could see the total items. But setting the SelectedValue didn't work. InOnDataBinding event, I couldn't even see the total items probably because the list isn't bound yet?
How can I set the selected index based on a value?
This seems to work for me.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownList1.DataBind(); // get the data into the list you can set it
DropDownList1.Items.FindByValue("SOMECREDITPROBLEMS").Selected = true;
}
}
DropDownList1.Items.FindByValue(stringValue).Selected = true;
should work.
This is working code
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownList1.DataTextField = "user_name";
DropDownList1.DataValueField = "user_id";
DropDownList1.DataSource = getData();// get the data into the list you can set it
DropDownList1.DataBind();
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText("your default selected text"));
}
}
Have you tried, after calling DataBind on your DropDownList, to do something like ddl.SelectedIndex = 0 ?

Resources