Listview Update not workng - c#

I'm trying to change the Select Command my DataSource uses using a dropdownlist. When the page loads it sets the select command depending on the selected index. When I change the dropdownlist the page refreshes but the data doesn't! Where am I going wrong?
.aspx file
<asp:DropDownList ID="filmFilter" runat="server" OnSelectedIndexChanged="filmFilter_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem Value="">Filter</asp:ListItem>
<asp:ListItem Value="priceASC">Price: Low-High</asp:ListItem>
<asp:ListItem Value="priceDSC">Price: High-Low</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionStringFilms %>"></asp:SqlDataSource>
<asp:ListView ID="ListView1" runat="server" DataKeyNames="filmID" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="ListView1_SelectedIndexChanged">
<ItemTemplate>
...
</ItemTemplate>
<LayoutTemplate>
...
</LayoutTemplate>
</asp:ListView>
code-behind - page load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (filmFilter.SelectedIndex == 0)
{
SqlDataSource1.SelectCommand = "SELECT * FROM [films]";
}
if (filmFilter.SelectedIndex == 1)
{
SqlDataSource1.SelectCommand = "SELECT * FROM [films] ORDER BY [filmPrice]";
}
if (filmFilter.SelectedIndex == 2)
{
SqlDataSource1.SelectCommand = "SELECT * FROM [films] ORDER BY [filmPrice] DESC";
}
}
}
Thanks!

You've got it so your datasource is set on the page_load which is fine but you've wrapped it in
if (!IsPostBack)
{
Which means your code to change the datasource will only happen when you are not in postback (when you change the value of the dropdown you will be in a postback)
Have a read through
http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx
It will help with your understanding

Related

How to get current item on Dropdownlist for ASP.NET

My design code :
<asp:DropDownList ID ="DropDownList1" runat="server" EnableViewState="true" AutoPostBack ="true" CssClass="ddl" DataSourceID="SqlDataSource1" DataTextField="CategoryName" DataValueField="CategoryId" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Categories]"></asp:SqlDataSource>
C# code:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("Products.aspx?catId=" + DropDownList1.SelectedValue);
}
In database category table:
Book 1
Movie 2
Game 3
Music 4
Book is always current item of drop down list. when i select others, their pages load but dropdownlist's current value is book and i can'response book's page.
Since you are doing a redirect, this means your page is being loaded again with the default binding, making first item selected by default, subscribe to the data bound event and perform selection based on the query string parameter.
ASPX
<asp:DropDownList OnDataBound="DropDownList1_DataBound" ...
C#
protected void DropDownList1_DataBound(object sender, EventArgs e)
{
if(!IsPostBack){
string selectedValue = Request.QueryString["catId"];
if(!string.IsNullOrEmpty(selectedValue))
DropDownList1.SelectedValue = selectedValue;
}
}
I think that the problem is that the list binds with the SqlDataSource on every postback so you are always getting the value of the first item.
To make sure that that's the problem, change the order of the select to DESC and see if you're always getting the last item.
change you're SQL to
SELECT * FROM [Categories] ORDER BY CategoryId DESC
And see if you're always getting 4.
If that's the problem then you need to bind the list by code always within page load like below:
if(!Page.IsPostback)
{
// code here
}
You can try two approach
Either move the dropdown populating code in the Page_Load and encapsulate the code with
if(!Page.IsPostBack)
{
//your code
}
or
<%
if(!Page.IsPostBack)
{ %>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Categories]"></asp:SqlDataSource>
<%}
%>

Drop-down Selected Value not Showing in my Detailview

I have drop-down that is not showing the previoiusly selected value in my Detailview. It always shows me the first value in the list. If the previously selected value was xyz then when the Detailvies loads, i want to show xyz. I have researched a lot but could not find any solution that i can use. please help
here is my aspx code for the field that has the dropdown
<asp:TemplateField HeaderText="Name:">
<ItemTemplate>
<asp:Label ID="lbl_UID" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Name") %>'></asp:Label></ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddl_Name" Width="200px" Height="25" DataSourceID="SDS_Manager" DataTextField="FULL_NM" AutoPostBack="false"
DataValueField="UID" runat="server" AppendDataBoundItems="false">
<asp:ListItem Text="Select Name" Value="Select Name"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
here is the code behind that binds the detailview
protected void Edit(object sender, EventArgs e)
{
using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
{
sqlcon.Open();
sqlcmd = new SqlCommand(#"Select PRJ_ID, WPC_CD, WPC_DESC, Name FROM myTable where PRJ_ID = '" + myvar + "' ", sqlcon);
da = new SqlDataAdapter(sqlcmd);
da.Fill(dt);
sqlcon.Close();
DV_Edit.DataSource = dt;
DV_Edit.DataBind();
sqlcon.Close();
popup.Show();
}
}
Try setting AutoPostBack="true" and make sure if you have any logic to set the value of the drop down in the page load, that the code is not executed on post back as shown below.
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
ddlOne.DataSource = //your data here;
ddlOne.DataBind();
}
}
//if you don't wrap this logic in the if(!IsPostBack), the code will simply re-populate
//the drop down and set the selected index to the first item in the list with each
//post back.

ASP.NET Get value from DropDownList in EditItemTemplate in codebehind

I have a GridView that I have placed in DropDownList's in 2 columns.
<asp:TemplateField HeaderText="Upgrade" SortExpression="Upgrade">
<ItemTemplate>
<asp:Label ID="LabelUpgrade" runat="server" Text='<%# Eval("Upgrade") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlUpgrade" runat="server" Width="100px">
<asp:ListItem Value="1">--Select--</asp:ListItem>
<asp:ListItem Value="2">1</asp:ListItem>
<asp:ListItem Value="3">2</asp:ListItem>
<asp:ListItem Value="4">3</asp:ListItem>
<asp:ListItem Value="5">4</asp:ListItem>
<asp:ListItem Value="6">5</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
how do I grab the item from ddlUpgrade in the codebehind?
OnUpdating Event - I don't have a way to pull the row to get the value from the drop down but I add my sql parameters here.
protected void IAP_Updating(object sender, SqlDataSourceCommandEventArgs e){}
RowUpdating Event - I can get the row here but I can't add the value to the sql parameters because e.command isn't valid here
protected void gvClients_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow _row = gvClients.Rows[e.RowIndex];
DropDownList _ddl = (DropDownList)_row.FindControl("ddlUpgrade");
SqlParameter _parm = new SqlParameter("#Upgrade", _ddl.SelectedItem.ToString());
}
On the RowUpdating event you can capture the control inside the edit template based on its ID.
GridViewRow row = GridView1.Rows[e.RowIndex];
DropDownList ddl = (DropDownList)row.FindControl("ddlUpgrade");
SqlParameter _parm = new SqlParameter("#Upgrade", ddl.SelectedItem.ToString());
e.Command.Parameters.Add(_parm);
I would add a hidden field outside the GridView:
<asp:HiddenField ID="hdnSelection" value="" runat="server" />
And change the gvClients_RowUpdating method:
protected void gvClients_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow _row = gvClients.Rows[e.RowIndex];
DropDownList _ddl = _row.FindControl("ddlUpgrade") as DropDownList;
if(_ddl != null)
{
hdnSelection.Value = _ddl.SelectedItem.Text;
IAP.Update();//Assuming IAP is the ID of the SqlDataSource
}
}
And my IAP_Updating method should look like this:
protected void IAP_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
SqlParameter _parm = new SqlParameter("#Upgrade", hdnSelection.Value);
e.Command.Parameters.Add(_parm);
}
I did not test the code. You may need to tweak.

Add values to DropDownList that's not represented in the db and still get SelectedValue asp.net

I have a couple of DropDownLists in my GridView from customer table that binds the selected value from my db.
I noticed that if I only have one customer and would like to edit that customers gender it's not possible because I populate the DropDownLists with the SELECT DISTINCT Gender FROM Customer and my first customer is either Herr or Frau and I can only choose from that value.
I was thinking I could solve this Problem using a Union select select
Gender
from
( select Gender = 'Herr'
union
select Gender = 'Frau'
)as Gender
to bring both alternatives but then i get this error message 'DropDownList1'** has a SelectedValue which is invalid because it does not exist in the list of items**
So my question is how can I add some alternatives to DropDownListsthat's not already presented in DB and still bind the SelectedValue?
<EditItemTemplate>
<asp:DropDownList ID="DropDownList3" runat="server" DataSourceID="SqlDataSource1" DataTextField="Gender" DataValueField="Gender" SelectedValue='<%# Bind("Gender") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:EventConnectionString %>" SelectCommand="SELECT DISTINCT [Gender] FROM [Customer]"></asp:SqlDataSource>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Gender") %>'></asp:Label>
</ItemTemplate>
Thanks for your answers, what do I Need to Change in code behind to make it work?
Here is my code behind.
protected void Page_Load(object sender, EventArgs e)
{
}
protected void lbInsert_Click(object sender, EventArgs e)
{
Event.InsertParameters["Gender"].DefaultValue = ((DropDownList)GridView1.FooterRow.FindControl("ddlGender")).SelectedValue;
Event.InsertParameters["LastName"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtLastName")).Text;
Event.InsertParameters["FirstName"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtFirstName")).Text;
Event.InsertParameters["Street"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtStreet")).Text;
Event.InsertParameters["HouseNr"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtHouseNr")).Text;
Event.InsertParameters["Zip"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtZip")).Text;
Event.InsertParameters["City"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtCity")).Text;
Event.InsertParameters["Phone"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtPhone")).Text;
Event.InsertParameters["Email"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtEmail")).Text;
Event.InsertParameters["Company"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtCompany")).Text;
Event.InsertParameters["Active"].DefaultValue = ((DropDownList)GridView1.FooterRow.FindControl("ddlActive")).SelectedValue;
Event.Insert();
}

How to retrieve text from dropdownlist?

I must audit the changes into a database. On most pages this works perfect, as there were just textboxes - however on a page I am working on right now, with dropdownlists, my code isn't working.
<td>
<asp:DropDownList ID="DropDownList4" runat="server" DataSourceID="SqlDatacountry" DataTextField="country_name" DataValueField="country_id">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDatacountry" runat="server" ConnectionString="<%$ ConnectionStrings:songtypecons %>" SelectCommand="SELECT * FROM [country_detail]"></asp:SqlDataSource>
</td>
code behind:
string sql1 = "selectcust_fname,cust_mname,cust_lname,cust_birthdate,cust_gender,cust_address,cust_contact_num,cust_country,cust_state,cust_city,cust_zip from cust_detail where cust_id ='" + ds.Tables["filldata"].Rows[0].ItemArray[0].ToString() + "' ";
SqlDataAdapter adpt1 = new SqlDataAdapter(sql1, con);
DataSet ds1 = new DataSet();
adpt1.Fill(ds1, "custdata");
if (ds1.Tables["custdata"].Rows.Count > 0)
{
for (int d = 0; d < DropDownList4.Items.Count; d++)
{
if (ds1.Tables["custdata"].Rows[0].ItemArray[7].ToString() == DropDownList4.Items[d].Text)
{
DropDownList4.Items[d].Selected = true;
break;
}
}
}
If I understand your question clearly, you just need to use your code in your ListControl.SelectedIndexChanged event.
Occurs when the selection from the list control changes between posts
to the server.
<asp:DropDownList ID="DropDownList4" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList4_SelectedIndexChanged" ...>
</asp:DropDownList>
protected void DropDownList4_SelectedIndexChanged(object sender, EventArgs e)
{
...
}
As I wrote in my comment, you should always use parameterized queries in your sql commands, your code is open for an SQL Injection attacks.

Categories