How do I set the Selected Value of a DropDownList inside an EditItemTemplate inside a DetailsView using the codebehind? - asp.net

I have a Details View on my ASP.NET (VB) page which lists the details of a customer (their name, address, etc).
The 'Country' option is a drop down list, pulled from a database table. This all works fine when viewing the Details View and you can see what country they are in.
However, when I click the Edit button on the DetailsView, the drop down list then shows all the available countries in the db table correctly but it has no selected value, so instead of selecting their currently-set country, it just defaults to the top one in the list. This is wrong as it's not their currently-set value.
Using the codebehind (VB), how should I set the selected value of the dropdown list to be the country name that they currently have set? In the codebehind, I have already read their current country name in and stored it in a string variable called strCurrentCountryName
eg.
Response.Write "strCurrentCountryName: " & strCurrentCountryName
Will show:
strCurrentCountryName: United Kingdom
So I now need to match their strCurrentCountryName value with one of the country names in the drop down list and set this as the SelectedValue for them.
My code in front (which lists all the countries in the db):
<asp:TemplateField HeaderText="Country" SortExpression="address5">
<EditItemTemplate>
<asp:SqlDataSource ID="SqlDataSourcecountryList" runat="server" ConnectionString="<%$ ConnectionStrings:PDConnectionString %>"
ProviderName="<%$ ConnectionStrings:PDConnectionString.ProviderName %>"
SelectCommand="SELECT country_name_short, country_name_long FROM country_list WHERE deleted = 0 ORDER BY country_name_long">
</asp:SqlDataSource>
<asp:DropDownList ID="DropDownListCountry" runat="server" CssClass="form-control"
DataSourceID="SqlDataSourcecountryList" DataTextField="country_name_long" DataValueField="country_name_short">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("address5") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
In the codebehind, I tried this (inside the Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load):
DropDownListCountry.DataBind()
DropDownListCountry.Items.FindByText(strCurrentCountryName).Selected = True
Which gives an error message of:
'DropDownListCountry' is not declared. It may be inaccessible due to its protection level
I tried using these two lines of code with the drop down list placed OUTSIDE of the EditItemTemplate and it works perfectly:
DropDownListCountry.DataBind()
DropDownListCountry.Items.FindByText(strCurrentCountryName).Selected = True
Sure enough, it does then correctly set their Selected Value to be the correct country.
In my codebehind (vb), do I need to somehow declare the DropDownListCountry first?
How do I make this work when placed inside the EditItemTemplate of my asp:TemplateField ?

Since the drop down is inside the template, it is not statically declared anywhere in the page's code, and so there is no way to reference it directly by just DropDownListCountry. Consider this - if that was possible, and you had a grid view template with these, drop down in which row would you be referencing?
So in reality this drop down gets assigned a different ID based on the container template it is in. So you need to find it inside the template on data binding time and then set the selected value the way you did:
Dim ddl As DropDownList = CType(detailsViewId.FindControl("DropDownListCountry"), DropDownList)
ddl.Items.FindByText(strCurrentCountryName).Selected = True
Important thing is to make sure that this code is run once drop down control was created. Most suitable place is right after data binding happend. To do so, subscribe to the DataBound event:
<asp:DropDownList ID="DropDownList1" runat="server" OnDataBound="DropDownList1_DataBound">
and run the code inside the event handler:
Protected Sub DropDownList1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs)
' Code above goes here
End Sub

Related

How to bind SelectedValue of DropdownList to DataSoruce when drop down is populated programmatically?

I have a GridView. When I go into edit mode on a row, I want one of the columns to be a dropdown. My first draft included this:
<asp:TemplateField HeaderText="Type">
<ItemTemplate>
<%# Eval("type_name") %>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ctlItemType" runat="server" datasourceid="dsItemTypes"
DataTextField="name" DataValueField="id"
selectedvalue='<%# Bind("item_type_id") %>' />
</EditItemTemplate>
</asp:TemplateField>
I should clarify that my data source included "type_name" as the name of the type and "item_type_id" as the ID corresponding to that name. That worked great. Cool.
But I need to restrict the values appearing in the drop down depending on other data about the record. So okay, fine, I removed the datasourceid, and instead populated the dropdown with code:
Private Sub ItemsGridView_RowDataBound(sender As Object, e As GridViewRowEventArgs)
Handles ItemsGridView.RowDataBound
If e.Row.RowState = DataControlRowState.Edit Then
Dim ctlItemType As DropDownList = e.Row.FindControl("ctlItemType")
Dim parent_id = ItemsGridView.DataKeys(e.Row.RowIndex).Values(1)
ctlItemType.DataSource = ItemTypeActions.List(parent_id)
ctlItemType.DataBind()
End If
End Sub
That blows up with a "SelectedValue not found" error, I presume because it's trying to set the selected value before I populate the values.
So I tried setting the SelectedValue in code also. After the DataBind above I added:
ctlItemType.SelectedValue = DataBinder.Eval(e.Row.DataItem, "item_type_id")
That displays fine when I go into edit mode, but when I click "Update", it blows up, because item_type_id doesn't get included in the list of parameters passed to the update function. Because it's not Bind'ed, it's just set with an Eval.
So how do I make this work? Is there a way to bind a control to a datasource with code? I could find anything like DataBinder.Eval that is equivalent to <%# bind("whatever") %>. Or ... what?

ASP.Net 4.5 Model Binding Cascading Drop Downs Null Reference (web Forms)

I'm retrofitting an older web forms site with Model Binding using asp.net 4.5.
In a DetailsView I have a drop down list that allows selection of a particular 'client' and another that allows selection of a particular 'project' that belongs to that client. So the drop down for project has to be filtered on the client number and if the user changes the client selection, I want to filter the project list by client number.
I couldn't figure out how to get the SelectedIndexChanged method on the client ddl to fire the Select method for the Project, so I concluded the only way to do it was to filter the project ddl by client number in all cases. I am getting an error message when the client selection is made:
NullReferenceException was Unhandled by User Code
which point in my aspx directly to the ddl for Projects.
This is an abbreviated version of the details view, you can see both the clients ddl and the projects ddl (I am operating in Edit mode):
<asp:DetailsView ID="AdministratorDetailsView" runat="server" AutoGenerateRows="False"
DataKeyNames="AdministratorNumber" ItemType="BusinessLogic.Administrator"
Width="99%"
SelectMethod="AdministratorDetailsView_GetItem"
UpdateMethod="AdministratorDetailsView_UpdateItem"
DeleteMethod="AdministratorDetailsView_DeleteItem"
FieldHeaderStyle-Width="30%" EditRowStyle-Width="99%"
InsertRowStyle-Width="70%" RowStyle-Width="99%" CssClass="admin"
AutoGenerateDeleteButton="true" AutoGenerateEditButton="true" >
<Fields>
<asp:TemplateField HeaderText="AdministratorCode" SortExpression="AdministratorCode">
<EditItemTemplate>
<asp:Label ID="AdministratorCode" Text="<%# Item.AdministratorCode%>" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="AdministratorCode" Text="<%# Item.AdministratorCode%>" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ClientNumber" SortExpression="ClientNumber">
<EditItemTemplate>
<asp:DropDownList ID="ddClients" runat="server"
AutoPostBack="true"
DataTextField="ClientName" DataValueField="ClientNumber"
ItemType="BusinessLogic.Client"
SelectMethod="ddClients_GetList"
SelectedValue="<%# Item.ClientNumber%>"
OnSelectedIndexChanged="AdministratorDetailsView_ddlClients_SelectedIndexChanged"/>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddClients" runat="server" Enabled="false"
DataTextField="ClientName" DataValueField="ClientNumber"
ItemType="BusinessLogic.Client"
SelectMethod="ddClients_GetList"
SelectedValue="<%# Item.ClientNumber%>"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Projects" >
<EditItemTemplate>
<asp:DropDownList ID="ddProjects" runat="server" AutoPostBack="true"
DataTextField="ProjectName" DataValueField="ProjectNumber"
ItemType="BusinessLogic.Project"
SelectMethod="ddProjects_GetList"
SelectedValue="<%# Item.ProjectNumber%>" />
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddProjects" runat="server" Enabled="false"
DataTextField="ProjectName" DataValueField="ProjectNumber"
ItemType="BusinessLogic.Project"
SelectMethod="ddProjects_GetList"
SelectedValue="<%# Item.ProjectNumber%>"/>
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
There are two SelectMethods, one for each drop down list, and a selectedindexchaneged method for clients:
Public Function ddClients_GetList() As List(Of BusinessLogic.Client)
Dim special As New List(Of Client)
special = CurrentClient.ClientList() 'add whole list
Dim NullClient As New Client()
NullClient.Load(0)
NullClient.ClientName = "<-Not Selected-->"
special.Add(NullClient) 'Had to have a client with 0 in the list since most admins don't have anything but 0 inthis field
Return special
End Function
Public Function ddProjects_GetList(<Control("ddClients")> ByVal ClientNumber As Integer) As List(Of BusinessLogic.Project)
Dim special As New List(Of Project)
If ClientNumber = 0 Then
special = CurrentProject.ProjectList() 'add whole list, refine it if Clients Drop Down selected
Else
special = CurrentProject.ProjectList(ClientNumber) 'add whole list, refine it if Clients Drop Down selected
End If
Dim NullProject As New Project()
NullProject.Load(0)
NullProject.ProjectName = "<-Not Selected-->"
special.Add(NullProject) 'Had to have a Project with 0 in the list since most admins don't have anything but 0 inthis field
Return special
End Function
Protected Sub AdministratorDetailsView_ddlClients_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim ddlProj As DropDownList
ddlProj = AdministratorDetailsView.FindControl("ddProjects")
ddlProj.ItemType = "BusinessLogic.Project"
ddlProj.DataBind()
End Sub
All is well until the user selects a different client which triggers the SelectIndexChanged event and then we get to the DataBind(), where we get the null exception (ddlProj is found).
Need some ideas on how to refresh the projects list based on the new client selection.
How do I force ddProjects to run its SelectMethod again, to avoid the null reference and reload the control?
Turns out this issue is not unique to ModelBinding, but is a General WebForms Issue.
You cannot have cascading dropdowns within another data control where they depend on each other unless you add a bit of code.
In my case, I was trying to bind both dropdowns to the underlying detailsview, and at the same time setting the selected values. Doesn't work because of timing. It seems right until you try to change the selection on the parent dropdown, and then you get null exception on the second because it is not yet loaded. It's all timing. If you try to work around it with saved values, it gets too messy.
My solution is, Bind another item to the underlying details view (you can make it hidden if you wish). Then add some code to keep it in sync with the actual value. DO NOT Bind SelectedValue on the secondary drop down , this is what causes the problem. Manage Selected Value in code using the added field.
<asp:DetailsView ID="AdministratorDetailsView" runat="server" AutoGenerateRows="False"
DataKeyNames="AdministratorNumber" ItemType="BusinessLogic.Administrator"
Width="99%" SelectMethod="AdministratorDetailsView_GetItem" UpdateMethod="AdministratorDetailsView_UpdateItem" DeleteMethod="AdministratorDetailsView_DeleteItem"
FieldHeaderStyle-Width="30%" EditRowStyle-Width="99%" InsertRowStyle-Width="70%" RowStyle-Width="99%" CssClass="admin" AutoGenerateDeleteButton="true" AutoGenerateEditButton="true"
>
<Fields>
<asp:TemplateField HeaderText="Client Name" SortExpression="ClientName">
<EditItemTemplate><asp:DropDownList ID="ddClients" runat="server" AutoPostBack="true" DataTextField="ClientName" DataValueField="ClientNumber" ItemType="BusinessLogic.Client" SelectMethod="ddClients_GetList" SelectedValue="<%# Item.ClientNumber%>" OnDataBound="ddClients_DataBound" OnSelectedIndexChanged="AdministratorDetailsView_ddlClients_SelectedIndexChanged" /> </EditItemTemplate>
<ItemTemplate><asp:DropDownList ID="ddClients" runat="server" Enabled="false" DataTextField="ClientName" DataValueField="ClientNumber" ItemType="BusinessLogic.Client" SelectMethod="ddClients_GetList" SelectedValue="<%# Item.ClientNumber%>"/></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Project Number" >
<EditItemTemplate><asp:Label ID="ProjectNumberLabel" runat="server" Text="<%# BindItem.ProjectNumber%>"></asp:Label></EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Project Name" SortExpression="ProjectNumber">
<EditItemTemplate><asp:DropDownList ID="ddProjects" runat="server" AutoPostBack="true" DataTextField="ProjectName" DataValueField="ProjectNumber" ItemType="BusinessLogic.Project" SelectMethod="ddProjects_GetList" OnDataBound="ddProjects_DataBound" OnSelectedIndexChanged="ddProjects_SelectedIndexChanged" />
</EditItemTemplate>
<ItemTemplate><asp:DropDownList ID="ddProjects" runat="server" Enabled="false" DataTextField="ProjectName" DataValueField="ProjectNumber" ItemType="BusinessLogic.Project" SelectMethod="ddProjects_GetList" SelectedValue="<%# Item.ProjectNumber%>" />
</ItemTemplate>
</asp:TemplateField>
</asp:DetailsView>
And in the code behind, not how we set and get the value of the bound projectnumber:
Protected Sub AdministratorDetailsView_ddlClients_SelectedIndexChanged(sender As Object, e As EventArgs)
''If this selection changes we need to change some flags and perhaps theProject ddl
''This causes null exception for Project ddl, can't figure out how to get it to reload. Tried DataBind(), same effect as having a ValueProvider in the parameters to the Select
Dim ProjectNumberLabel As Label = AdministratorDetailsView.FindControl("ProjectNumberLabel")
ProjectNumberLabel.Text = "0" 'Synchronize to no selection
Dim ddProjects As New DropDownList
ddProjects = AdministratorDetailsView.FindControl("ddProjects") 'Have to use Find Control because ddl is buried in DetailsView
ddProjects.SelectedValue = 0 'Cause it to read Select an Item
ddProjects.DataBind() 'Rebinding it causes the SelectMethod to run.
End Sub
Protected Sub ddProjects_DataBound(sender As Object, e As EventArgs)
'Because of the problem with cascading references, we had to remove the SelectValue declaration from ddProjects.
'So we must make sure that once theddProjects is databound, it points to the selected value from the data
Dim ddlProjects As DropDownList
ddlProjects = AdministratorDetailsView.FindControl("ddProjects")
Dim ProjectNumberLabel As Label = AdministratorDetailsView.FindControl("ProjectNumberLabel")
ddlProjects.SelectedValue = CInt(ProjectNumberLabel.Text)
End Sub
Hope someone else sees this as useful. I couldn't find it anywhere.
Great posting, as I faced a similar conundrum and it made me think. I have done this before outside of the model-binding approach, and the solution is essentially the same, as described. I used a ListView, and added the method:
OnItemDataBound="lvWhatever_ItemDataBound"
to fire an event from which to go and get the relevant ID from another bound control in the list view data item:
if (e.Item.ItemType == ListViewItemType.DataItem)
{
// get the ID from from another control in this item record: lblItemID
ListViewDataItem lvdi = (ListViewDataItem)e.Item;
if (lvdi != null)
{
Label iID = (Label)lvdi.FindControl("lblItemID");
if (iID != null)
where lblItemID.Text contains the relevant ID. Then from that I can query to get the relevant list, and manually bind it to the DDL. Brilliant - thanks very much.

How can I disable/hide edit button in gridview control of ASP.net

I have a gridview control in which there are two command buttons (linkButton), one is "select" and the other is "edit", now I have a session variable named as department and it contains values like "WRITING", "EDITING", "ADMIN" etc... Now the thing is I want the edit button to disappear when the department is "WRITING" but when it is "EDITING" or "ADMIN" I want edit button appear.
I was searching some forums for this problem and found this
row.Cells[0].Controls.Clear();
The problem with this code is that it hides the entire command column including "select" and "edit" buttons while I only want to control "edit" button, select should remain visible for all departments.
if I do it like (on row data bound event)
e.row.Cells[0].Controls[1].visible = false OR
e.row.Cells[0].Controls[0].visible = false
Specified argument was out of the range of valid values.
How can I do this properly ?
Thanks.
You can use the Visible property in the following way.
if (Session(mode) == "WRITING")
{
(e.Row.FindControl("btnEdit")).Visible = false;
}
First of all - your code does not work because your gridViewCell at index 0 contains only one control. Every CommandButton gets a single cell! Furthermore I am not quite sure why you make use of the RowDataBound event. As you are using a Session-Var this one may not change while binding your rows.
I tried the following piece of code in my pageLoad eventHandler - and it worked out for me:
/// just replace CAPITAL letters with your names and
/// (Session["department"] == "WRITING") with your boolean expression
gvYOURGV.Columns[INDEXOFSELECTCOLUMN].Visible = (Session["department"] == "WRITING");
In case you do want to have (need to have?) more flexibilty on modifying the appearance of your command columns - you may even consider, changing your command columns to templated columns. Doing so you may have the possibility for this code:
<asp:GridView ID="gvYOURGV" runat="server">
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1"
visible='<%# Session["department"] != "WRITING" %>'
runat="server" CausesValidation="False"
CommandName="Select" Text="Auswählen"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
hth

Loading a value on the insert command of a detailsview

In a detailsview, how can I prepopulate one of the textboxes on the insertcommand (When the user clicks insert and the view is insert).
I think this would work for codebehind:
Dim txtBox As TextBox = FormView1.FindControl("txtbox")
txtbox.Text = "Whatever I want"
Is this right? What do I need in the aspx (not as sure)? Also, I'm assuming the server-side code will go in the itemcommand or insertcreating event.
I have typed this in VB.NET but I am using C# (I can do both so on a language agnostic forum I might type the problem in another language). I am also using a SqlDataSource, with my parameters and insert/delete/edit commands all created.
I am trying to generate a random GUID (using the GUID object), which will be prepopulated in the textbox.
Also, is the postbackurl property of a button not another way of preserving form state?
Thanks
I would update the field in the DetailsView to a TemplateField:
<asp:TemplateField>
<InsertItemTemplate>
<asp:TextBox ID="txtField" runat="server" Text='<%# Bind("GUID") %>'/>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="lblField" runat="server" Text='<%# Bind("GUID") %>'/>
</ItemTemplate>
</asp:TemplateField>
Then you have two options:
generate your GUID and insert into
your datasource. This may have to be done with SQL since you mentioned using SqlDataSource
remove the binding and access the controls from code in the
DataBound event of your DetailsView
Private Sub dv_DataBound(ByVal sender As Object, ByVal e As EventArgs) Handles dv.DataBound
dim txt as Textbox = dv.FindControl("txtField")
txt.Text = GenerateGUID()
End Sub
I'm guessing you need to use one of detailsview events.
Hook up to ItemCommand, ModeChanging or ModeChanged events and fill your value there.
I am doing something like this as well. I am hiding the DetailsView and showing it when the user clicks a button.
dvDetails.ChangeMode(DetailsViewMode.Insert)
pnlDetailMenu.Visible = True
Dim ColumnTextBox As TextBox
ColumnTextBox = dvDetails.Rows(0).Cells(1).Controls(0)
If Not ColumnTextBox Is Nothing Then
ColumnTextBox.Text = "Initial Value"
End If

Databound drop down list - initial value

How do I set the initial value of a databound drop down list in ASP.NET?
For instance, I want the values, but the first value to display should be -- Select One ---, with a null value.
I think what you want to do is this:
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="--Select One--" Value="" />
</asp:DropDownList>
Make sure the 'AppendDataBoundItems' is set to true or else you will clear the '--Select One--' list item when you bind your data.
If you have the 'AutoPostBack' property of the drop down list set to true you will have to also set the 'CausesValidation' property to true then use a 'RequiredFieldValidator' to make sure the '--Select One--' option doesn't cause a postback.
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="DropDownList1"></asp:RequiredFieldValidator>
I know this is old, but a combination of these ideas leads to a very elegant solution:
Keep all the default property settings for the DropDownList (AppendDataBoundItems=false, Items empty). Then handle the DataBound event like this:
protected void dropdown_DataBound(object sender, EventArgs e)
{
DropDownList list = sender as DropDownList;
if (list != null)
list.Items.Insert(0, "--Select One--");
}
The icing on the cake is that this one handler can be shared by any number of DropDownList objects, or even put into a general-purpose utility library for all your projects.
What I do is set the text property of the drop down list AFTER I databind it. Something like this:
protected void LoadPersonComboBox()
{
var p = new PeopleBLL();
rcmbboxEditPerson.DataSource = p.GetPeople();
rcmbboxEditPerson.DataBind();
rcmbboxEditPerson.Text = "Please select an existing person to edit...";
}
This makes the initial visible value of this dropdown show up, but not actually be a part of the drop down, nor is it a selectable.
I know this already has a chosen answer - but I wanted to toss in my two cents.
I have a databound dropdown list:
<asp:DropDownList
id="country"
runat="server"
CssClass="selectOne"
DataSourceID="country_code"
DataTextField="Name"
DataValueField="CountryCode_PK"
></asp:DropDownList>
<asp:SqlDataSource
id="country_code"
runat="server"
ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
SelectCommand="SELECT CountryCode_PK, CountryCode_PK + ' - ' + Name AS N'Name' FROM TBL_Country ORDER BY CountryCode_PK"
></asp:SqlDataSource>
In the codebehind, I have this - (which selects United States by default):
if (this.IsPostBack)
{
//handle posted data
}
else
{
country.SelectedValue = "US";
}
The page initially loads based on the 'US' value rather than trying to worry about a selectedIndex (what if another item is added into the data table - I don't want to have to re-code)
To select a value from the dropdown use the index like this:
if we have the
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true"></asp:DropDownList>
you would use :
DropDownList1.Items[DropDownList1.SelectedIndex].Value
this would return the value for the selected index.
hi friend in this case you can use the
AppendDataBound="true"
and after this use the list item.
for e.g.:
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="--Select One--" Value="" />
</asp:DropDownList>
but the problem in this is after second time select data are append with old data.
Add an item and set its "Selected" property to true, you will probably want to set "appenddatabounditems" property to true also so your initial value isn't deleted when databound.
If you are talking about setting an initial value that is in your databound items then hook into your ondatabound event and set which index you want to selected=true you will want to wrap it in "if not page.isPostBack then ...." though
Protected Sub DepartmentDropDownList_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles DepartmentDropDownList.DataBound
If Not Page.IsPostBack Then
DepartmentDropDownList.SelectedValue = "somevalue"
End If
End Sub
dropdownlist.Items.Insert(0, new Listitem("--Select One--", "0");

Resources