ASP.Net DropDownList Retains Value From Database - AutoPostBack - sql

I have been stuck in this problem for along time, searched online but no solution yet solved my problem. I have a dropdownlist where it retrieved the plan names from a table in my databse based on the zip code that is entered in a text field. The problem I am running into is: when I enter a zip code, the plan names populate with no problem in the dropdownlist, then I select one of the plans, when I go further and try to enter other info in other fields which have autppostback = true, the dropdownlist does not retain its value and always select the first value, I want the dropdownlist to retain the selected value after the postback, here is my code:
step1.aspx
<p>
<asp:TextBox ID="txt_zip_code" runat="server" AutoPostBack="true"></asp:TextBox>
</p>
<p>
<asp:DropDownList ID="dd_dental_plan" runat="server" EnableViewState="true">
</asp:DropDownList>
</p>
step1.cs
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CustomerDataConnectionString"].ConnectionString))
{
using (SqlCommand sqlCmd = new SqlCommand())
{
sqlCmd.CommandText = "SELECT * FROM [dbo].[mfd_plans] WHERE zip_code = #zipCode";
sqlCmd.Parameters.AddWithValue("#zipCode", txt_zip_code.Text);
sqlCmd.Connection = conn;
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
DataTable dt = new DataTable();
da.Fill(dt);
dd_dental_plan.DataSource = dt;
dd_dental_plan.DataValueField = "plan_id";
dd_dental_plan.DataTextField = "plan_name";
dd_dental_plan.DataBind();
conn.Close();
dd_dental_plan.Items.Insert(0, new ListItem("Please select plan", "0"));
}
}

you should use update panel on your aspx page for preventing whole page load when autopostback occurs from another fields.
just put an asp:scriptmanager control on your page. After the put your zip code and dropdownlist into update panel and put other controls in separate update panels by which post back occurs. your code will look like this.
<asp:ScriptManager runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<p>
<asp:TextBox ID="txt_zip_code" runat="server" AutoPostBack="true"></asp:TextBox>
</p>
<p>
<asp:DropDownList ID="dd_dental_plan" runat="server" EnableViewState="true">
</asp:DropDownList>
</p>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
another controls which caused postback event
</ContentTemplate>
</asp:UpdatePanel>
another controls which don't cause postback.
</div>
Hope this will works.enter code here
Thanks

Umm I really hoped that I understand your Question correctly ..
Have you tried something like
if (!Page.IsPostBack)
{// All the code that you've written above ..}
and do that with all you're codes that you write in Page_Load ...
give it a try ...

Related

How to Add an Empty, Unbound, Comment Column to a GridView?

I've put together a GridView table in ASP.net that allows users to approve a series of records. As part of this approval process, I'd like to provide an empty column for the user to provide comments where necessary. The only records showing up will be records that haven't been approved yet, thus, no comments will need to be loaded. Once they are approved, users will not be able to view these records again.
How do I go about adding this empty column to my GridView? Again, there's no data to load into this column. Once approved, the records in the SQL Server table will be updated with a timestamp and comments.
Most of what I was able to find on here so far has been related to adding empty rows, but not columns. I'm completely new to ASP.net, so any help would be greatly appreciated.
Current Column Code:
asp:TemplateField HeaderText="Comment" ItemStyle-Width="500px" ItemStyle-Wrap="true" SortExpression="Comment" /
Just a simple solution I've quickly put together. It uses the OnRowCommand event of the GridView.
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="TextBox">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Text='<%# Eval("textfield") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UpdateButton">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Update" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
//cast the sender back to a gridview
GridView gv = sender as GridView;
//cast the commandsource back to a button
Button btn = e.CommandSource as Button;
//cast the namingcontainer of the button back to a gridviewrow
GridViewRow row = btn.NamingContainer as GridViewRow;
//find the correct textbox using findcontrol and the index obtained from the row
TextBox tb = gv.Rows[row.DataItemIndex].FindControl("TextBox1") as TextBox;
//show result
Label1.Text = tb.Text;
}
UPDATE
Or if you want to update all the records at once by pressing a button.
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
TextBox tb = row.FindControl("TextBox1") as TextBox;
Label1.Text += tb.Text + "<br>";
}
}

Find Radiobutton Control from ID String in vb.net

I have 3 radiobuttons in my aspx:
<asp:RadioButton ID="rdoMasculin"
runat="server" AutoPostBack="true"
Checked="true" GroupName="gender"
TextAlign="Right" />
<asp:RadioButton ID="rdoFeminin"
runat="server" AutoPostBack="true"
GroupName="gender" />
<asp:RadioButton ID="rdoAnonymous"
runat="server" AutoPostBack="true"
GroupName="gender" />
When sending the form I'm storing the ID of the checked radiobutton in a Session variable:
for example: Session("currentGender") = rdoZukuTermine.ID
When I'm getting back on the page in a later stage I'm using the following code in codebehind:
Dim currentRadio = CType(FindControl(Session("currentGender")), RadioButton)
currentRadio.Checked = True
Session.Remove("currentGender")
currentRadio ends up as a null reference. But when I'm checking the Session it contains the right ID as a string.
Can someone help me?
Is the RadioButton control directly in your .aspx or does it have any parent controls? if yes call Findcontrol() on it direct parent like this:
Dim currentRadio = CType(ParentControl.FindControl(Session("currentGender")), RadioButton)

HTML MAILTO hyperlink doesn't respond

My hyperlink doesn't open up an email with my database text value.
I have a previous application that uses this exact format and works; however, for this application it doesn't.
One of the many examples I have referenced is: ASP.NET mailto: misfunction
my Database column name is email_Own and so I have tried to DataItem.email_Own and DataItem.email like other examples show to see if whether the value after DataItem is the database column name or not. Both don't work.
Working EX
My other application showed an email within a gridview so I am wondering if that is the reason why the coding below worked:
<asp:TemplateField HeaderText="Description" >
<ItemTemplate >
<br /><br />
Email:
<asp:HyperLink id="lnkEmail" cssClass="emailColor" runat="server" text='<%#DataBinder.Eval(Container, "DataItem.email") %>' NavigateUrl='<%#DataBinder.Eval(Container, "DataItem.email","MAILTO:{0}")%>'>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
Coding that doesn't work:
Any suggestions for the coding below? This hyperlink is inside a table.
<tr>
<td width="25%">
<font class="Blackfont" size="2" > <b>Owner Email </b> </font>
</td>
<td>
<asp:HyperLink id="Owner_E" runat="server" text='<%#DataBinder.Eval(Container, "DataItem.email") %>' NavigateUrl='<%#DataBinder.Eval(Container, "DataItem.email","MAILTO:{0}")%>'Font-Size="10pt"></asp:HyperLink>
</td>
</tr>
The text of the hyperlink shows up correctly when the page loads. Its the linking to mail that isn't working.
I also tried this code snippet instead but the hyperlink doesn't respond as well: NavigateUrl='<%#Bind("email_Own", "mailto:{0}") %>' Text='<%#Bind("email_Own") %>'
FYI:
I am not sure if this changes anything but I fill the hyperlink in VB.net like so:
If Not DsAds.Tables(0).Rows(0).Item(14) Is DBNull.Value Then
lnkEmail.Text = DsAds.Tables(0).Rows(0).Item(14)
End If
where DsAds is a dataset
The HTML source code shows this:
I referenced http://forums.asp.net/t/1071308.aspx?mailto+link+in+textbox
Like so:
<asp:HyperLink id="lnkEmail" runat="server" Font-Size="10pt" ></asp:HyperLink>
and in Page Load[at end of it] I add:
lnkEmail.NavigateUrl = "mailto:" + DsAds.Tables(0).Rows(0).Item(14)
lnkEmail.Text = DsAds.Tables(0).Rows(0).Item(14)

Multiple Outputs From One Set of Labels

I am building a website in ASP.NET Web Forms with a SQL Database. The database contains a table with 571 entry's of data.
Output
Source Code
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand command = new SqlCommand("SELECT Id, Name, Townland, Near, Status, Built FROM Houses ORDER BY Name DESC", connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
lblId.Text = reader[0].ToString();
lblName.Text = reader[1].ToString();
lblTown.Text = reader[2].ToString();
lblNear.Text = reader[3].ToString();
lblStatus.Text = reader[4].ToString();
lblBuilt.Text = reader[5].ToString();
}
}
}
}
Database
I want to display all 571 houses to do this I would need a set of labels for each house but is there a way I could have one set of labels like the above code to output all 571 entry's without repeating code.
Try to use a Repeater. This is a special control, which allows to define an inner item layout only once and then bind some data to render multiple blocks looking consistently, but containing the different data.
Repeater has ItemTempalte property, which allows you to wrap all the labels you want to see.
<asp:Repeater ID="rptData" runat="server">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("Id") %>'></asp:Label>
<asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:Repeater>
Then just load the DB rows into repeater:
rptData.DataSource = command.ExecuteReader();
rptData.DataBind();
And finally, in the HTML layout specify mapping for labels to respective columns - like
<asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label>
or
<asp:Label runat="server" Text='<%# Eval("Townland") %>'></asp:Label>
etc.

how to pass variable in the url from gridview in vb.net

I have Gridview of the form results. I am trying to add an url to one of the field. How do I pass the variable in the url. intLib is the variable. This is what I have:
VB.Net Code:
<a href="EditIncident.aspx?ID=<%# Eval("Inci_ID")%>&Val2="& intLib>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Inci_ID") %>'></asp:Label>
</a>
I created a session variable and passed it on to the next page.
Thanks for your help.