Reloading drop down box in asp.net detailsview - asp.net

In a detailsview I have a drop down list whose selection determines the list in a second Drop down list. When the web page loads all my "Get Data" Functions load the various Drop down boxes. After I make a selection in the first of the two related drop down boxes I call an "index changed" function that takes the value of the first drop down box, as a variable, and puts it into a SQL statement. This SQL statement runs correctly inside SQL. However, the second drop down doesn't reload with the new data the values in the second drop down remain the same. Here is the pertinent code:
` <asp:TemplateField HeaderText="Planting Hatchery">
<ItemTemplate>
<asp:Label ID="lblPlantHatch" runat="server" Text='<%# Eval ("HatcheryCodePlant")%>' Visible = "true"></asp:Label>
</ItemTemplate>
<insertItemTemplate>
<asp:DropDownList ID="ddPlantingHatchery" runat="server" DataSource='<%# GetPlantingHatchery()%>'DataTextField="HatcheryNamePlant" DataValueField="HatcheryCodePlant" width= "150" AppendDataBoundItems="true" AutoPostBack="true"
OnSelectedIndexChanged="ddPlantingHatchery_indexchanged">
<asp:ListItem Text="Select" Value="" />
</asp:DropDownList>
</insertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Water Body Name">
<ItemTemplate>
<asp:Label ID="lblStreamName" runat="server" Text='<%# Eval("CatalogNo")%>' Visible = "true"></asp:Label>
</ItemTemplate>
<insertItemTemplate>
<asp:DropDownList ID="ddCatalogName" runat="server" DataSource='<%# GetCatalogNames()%>'
DataTextField="StreamName" DataValueField="CatalogNo" AppendDataBoundItems="true" >
<asp:ListItem Text="Select" Value="" />
</asp:DropDownList>
<asp:ObjectDataSource ID="dsWaterBody" runat="server" TypeName="StreamName"
<SelectMethod="GetCatalogNames">
<SelectParameters>
<asp:ControlParameter Name="HatcheryCodePlant" Type="string" ControlID="ddPlantingHatchery" PropertyName="Selectedvalue"/>
</SelectParameters>
</asp:ObjectDataSource>
</insertItemTemplate>`
This is the Code Behind:`
Public Function GetPlantingHatchery() As DataSet
Dim myConnection As New SqlConnection(ConnectionString)
Dim ad As New SqlDataAdapter("SELECT HatcheryNamePlant, HatcheryCodePlant FROM HatcheryPlant Order by HatcheryNamePlant", myConnection)
Dim ds As New DataSet()
ad.Fill(ds, "HatcheryPlant")
Return ds
End Function
Public Function GetCatalogNames() As DataSet
Dim myConnection As New SqlConnection(ConnectionString)
Dim ad As New SqlDataAdapter("SELECT StreamName, CatalogNo, HatcheryNamePlant, HatcheryCodePlant, LLID FROM vwStockingWatersByHatchery Order By StreamName", myConnection)
Dim dsWaterBody As New DataSet()
ad.Fill(dsWaterBody, "Catalog")
Return dsWaterBody
End Function
Public Function ddPlantingHatchery_indexchanged(sender As Object, e As EventArgs)
Try
Dim ddCatNum As DropDownList = TryCast(dvSMasterCurrentYear.FindControl("ddCatalogName"), DropDownList)
'ddCatNum.SelectedValue = TryCast(dvSMasterCurrentYear.FindControl("ddPlantingHatchery"), DropDownList).SelectedValue
MySelectedValue = TryCast(dvSMasterCurrentYear.FindControl("ddPlantingHatchery"), DropDownList).SelectedValue
Dim myConnection As New SqlConnection(ConnectionString)
Dim ad As New SqlDataAdapter("SELECT StreamName, CatalogNo, HatcheryNamePlant, HatcheryCodePlant, LLID FROM vwStockingWatersByHatchery where HatcheryCodePlant = '" + MySelectedValue + "' Order By StreamName", myConnection)
Dim dsWaterBody As New DataSet()
ad.Fill(dsWaterBody, "Catalog")
Return dsWaterBody
Catch ex As Exception
End Try`
What do I need to do to load the second Drop down list with the new data?

Related

Bind Listview Inside Listview for sub menus(child menus)

I am little confused for creating website menu & sub menus which is completely dynamic & made from database. For Menus I used Listview Control which is fine now all menus have submenus(child menu) as well which is based on menus. Now I don't understand how to do it. I guess using nested ListView would be good for this but I need an hint how to bind nested listview?
This is my main Listview
<asp:ListView ID="mainMenu" runat="server">
<ItemTemplate>
<li><asp:HyperLink ID="mainLinks" runat="server" NavigateUrl='<%# Eval("name", "~/{0}") %>' Text='<%# Eval("name") %>'></asp:HyperLink>
<ul class="super-child">
<asp:ListView ID="childMenu" runat="server">
<ItemTemplate>
<li><asp:HyperLink ID="cat3" runat="server" NavigateUrl='<%# Eval("category") & Eval("name", "/{0}") %>' Text='<%# Eval("name") %>'></asp:HyperLink></li>
</ItemTemplate>
</asp:ListView>
</ul>
</li>
</ItemTemplate>
</asp:ListView>
Private Sub bigMenu()
Dim constr As String = ConfigurationManager.ConnectionStrings("conio").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand()
cmd.CommandText = "SELECT * FROM mainMenu WHERE status = 'active' order by CAST(position as SIGNED INTEGER) asc"
cmd.Connection = con
Using sda As New MySqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
mainMenu.DataSource = dt
mainMenu.DataBind()
End Using
End Using
End Using
End Sub
You need to use ListView ItemDataBound to bind your nested listview. ItemDatBound will get rows value for you. See the below code I done for you
<asp:ListView ID="mainMenu" runat="server" DataKeyNames="enter column name you want">
<ItemTemplate>
<li><asp:HyperLink ID="mainLinks" runat="server" NavigateUrl='<%# Eval("name", "~/{0}") %>' Text='<%# Eval("name") %>'></asp:HyperLink>
<ul class="super-child">
<asp:ListView ID="childMenu" runat="server">
<ItemTemplate>
<li><asp:HyperLink ID="cat3" runat="server" NavigateUrl='<%# Eval("category") & Eval("name", "/{0}") %>' Text='<%# Eval("name") %>'></asp:HyperLink></li>
</ItemTemplate>
</asp:ListView>
</ul>
</li>
</ItemTemplate>
</asp:ListView>
Protected Sub onItemDataBound(sender As Object, e As ListViewItemEventArgs)
If e.Item.ItemType = ListViewItemType.DataItem Then
Dim itm As ListViewDataItem = CType(e.Item, ListViewDataItem)
Dim name As String = mainMenu.DataKeys(itm.DataItemIndex)("enter your datakeyname")
Dim childMenu As ListView = TryCast(e.Item.FindControl("childMenu"), ListView)
Dim constr As String = ConfigurationManager.ConnectionStrings("conio").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand()
cmd.CommandText = "SELECT * FROM tablename WHERE column = '" + name + "'"
cmd.Connection = con
Using sda As New MySqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
childMenu.DataSource = dt
childMenu.DataBind()
End Using
End Using
End Using
End If
End Sub

Linking SqlDataSource to label for a single item in ASP.NET

I have a asp:SqlDataSource that returns a single row. How do I return that value into a label. I got it working in a asp:DataList but its overkill since its a single record.
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionString %>"
SelectCommand="SELECT STATEMENT">
</asp:SqlDataSource>
<asp:DataList ID="DataList5" runat="server" DataSourceID="SqlDataSource2">
<ItemTemplate>
<asp:Label ID="label1" runat="server" Text='<%# Eval("ID") %>'></asp:Label><br />
</ItemTemplate>
</asp:DataList>
Here is one way to do it in C#:
DataView oDV = (System.Data.DataView)SqlDataSource2.Select(DataSourceSelectArguments.Empty);
Label1.Text = string.Join("|", oDV.Table.Rows[0].ItemArray.Select(p => p.ToString()).ToArray());
I guess my project is using an actual method instead of a property like I first suggested.
You could use a text SqlCommand(String, SqlConnection), passing the select statement and a SqlConnection(String) to your database.
public string GetSelectStatement()
{
SqlConnection conn = new SqlConnection(ConnectionString);
string selectStatement = "SELECT TOP 1 ID FROM Customer";
SqlCommand comm = new SqlCommand(selectStatement, conn);
comm.CommandType = System.Data.CommandType.Text;
SqlDataReader reader = comm.ExecuteReader();
// My code has a while, but you shouldn't need it with only one record
reader.Read();
string ID = (string)reader["ID"];
return ID;
}
Then in your page (aspx) or control (ascx) you can use that method to bind the label text
<asp:Label ID="label1" runat="server" Text='<%# GetSelectStatement() #>'></asp:Label>

Get a DropDownList item from a Gridview

I'm using Visual Basic with ASP.NET. I have a GridView table with a DroDownList column and I need a way to get the selected item from it. Now I'm using an ImageButton in order to get the selected item from the DropDownList to pop-up as a message box. I already know how to get an integer from a boundfield. However, using the same code to get the DropDownList item won't work.
This is a snippet from my code:
ASP code:
<asp:BoundField DataField="Case#" HeaderText="Case#" ReadOnly="True" />
<asp:TemplateField HeaderText="Surgery Time">
<ItemTemplate>
<asp:DropDownList ID="Time_Slot" runat ="server">
<asp:ListItem Selected="True" Value="0">Select...</asp:ListItem>
<asp:ListItem Value="1">8:00</asp:ListItem>
<asp:ListItem Value="2">9:00</asp:ListItem>
<asp:ListItem Value="3">10:00</asp:ListItem>
<asp:ListItem Value="4">11:00</asp:ListItem>
<asp:ListItem Value="5">12:00</asp:ListItem>
<asp:ListItem Value="6">1:00</asp:ListItem>
<asp:ListItem Value="7">2:00</asp:ListItem>
<asp:ListItem Value="8">3:00</asp:ListItem>
<asp:ListItem Value="9">4:00</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField buttontype="Image" ImageUrl="~/Images/check.jpg" commandname="Accept" HeaderText="Accept" SortExpression="Accept" />
Visual Basic code:
Sub GridView_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
If e.CommandName = "Accept" Then
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
Dim selectedRow As GridViewRow = GridView1.Rows(index)
'This value is retrieved from the databound
Dim contactCell As TableCell = selectedRow.Cells(0)
Dim contact As String = contactCell.Text
'however here it is not retrieved from the dropdownlist
Dim contactCell2 As TableCell = selectedRow.Cells(1)
Dim contact2 As String = contactCell2.Text
MsgBox("case number is" + contact + "time is" + contact2)
End If
End Sub
Try this.
If e.CommandName = "Accept" Then
Dim index = e.CommandArgument
Dim timeSlot = CType(gridview1.Rows(index).FindControl("Time_Slot"), DropDownList)
Dim selectedTimeSlot = timeSlot.SelectedValue
End If

GridView RowEditing event only fires on alternate rows

I have a GridView as below:
<asp:GridView ID="gvChain" runat="server" Font-Size="Small" CellPadding="3" CellSpacing="1" GridLines="None"
AutoGenerateColumns="False">
<HeaderStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField HeaderText="Department" ControlStyle-Width="175px">
<EditItemTemplate>
<asp:Label ID="lblDepartment" runat="server" Text='<%# Bind("Department") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblDepartment" runat="server" Text='<%# Bind("Department") %>'></asp:Label>
</ItemTemplate>
<ControlStyle Width="175px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Manager Level 1" ControlStyle-Width="175px">
<ItemTemplate>
<asp:Label ID="lblManager1" runat="server" Text=""></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="cbManager1" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ControlStyle Width="175px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Manager Level 2" ControlStyle-Width="175px">
<ItemTemplate>
<asp:Label ID="lblManager2" runat="server" Text=""></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="cbManager2" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ControlStyle Width="175px" />
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" CommandName="Edit" runat="server" Text="Edit" CssClass="buttonStyle" CausesValidation="false"/>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnSave" CommandName="Update" runat="server" Text="Save" CssClass="buttonStyle" CausesValidation="false"/>
<asp:LinkButton ID="btnCancel" CommandName="Cancel" runat="server" Text="Cancel" CssClass="buttonStyle" CausesValidation="false" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnDelete" CommandName="Delete" runat="server" Text="Delete" CssClass="buttonStyle" CausesValidation="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The BoundField is populated in the Page_Load event as below:
Dim dHandler As DepartmentHandler = New DepartmentHandler
Dim depts As New List(Of Department)
depts = dHandler.GetDepartmentList
gvChain.DataSource = depts.
If Not Page.IsPostBack Then
gvChain.DataBind()
End If
Populating of the TemplateFields is then done in the RowDataBound event as below:
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.RowState = DataControlRowState.Edit Then
Dim cbManager1 As DropDownList = TryCast(e.Row.FindControl("cbManager1"), DropDownList)
Dim cbManager2 As DropDownList = TryCast(e.Row.FindControl("cbManager2"), DropDownList)
Dim eHandler As EmployeeHandler = New EmployeeHandler
' Get the list of managers
Dim mgrs As New List(Of Manager)
mgrs = eHandler.GetManagerList
cbManager1.DataSource = mgrs
cbManager2.DataSource = mgrs
cbManager1.DataValueField = "Name"
cbManager1.DataTextField = "Name"
cbManager2.DataValueField = "Name"
cbManager2.DataValueField = "Name"
cbManager1.DataBind()
cbManager2.DataBind()
' Get the department name from the label in cell 0
Dim lbl As Label = e.Row.Cells(0).FindControl("lblDepartment")
Dim dept As Department = New Department
dept.Department = lbl.Text
' Pass the department name to the getManager1/2 functions to return the correct manager for that department
Dim mgr1 As Manager = eHandler.getManager1(dept)
Dim mgr2 As Manager = eHandler.getManager2(dept)
' Upper case the manager name to search the DDLs for item
Dim mgr1Name As String = mgr1.Name.ToUpper()
Dim mgr2Name As String = mgr2.Name.ToUpper()
' Find the manager in the DDL and select
cbManager1.SelectedValue = mgr1Name
cbManager2.SelectedValue = mgr2Name
Else
' If GV isnt in edit mode then populate labels in itemtemplate with manager 1 and 2 values
Dim lblManager1 As Label = DirectCast(e.Row.FindControl("lblManager1"), Label)
Dim lblManager2 As Label = DirectCast(e.Row.FindControl("lblManager2"), Label)
Dim eHandler As EmployeeHandler = New EmployeeHandler
Dim lbl As Label = e.Row.Cells(0).FindControl("lblDepartment")
Dim dept As Department = New Department
dept.Department = lbl.Text
Dim mgr1 As Manager = eHandler.getManager1(dept)
Dim mgr2 As Manager = eHandler.getManager2(dept)
lblManager1.Text = mgr1.Name
lblManager2.Text = mgr2.Name
End If
End If
I then have the below in the RowEditing event
gvChain.EditIndex = e.NewEditIndex
gvChain.DataBind()
When there is only 1 record displayed in the GridView, I click the edit button and the GridView goes into Edit mode I am able to update that record using the RowUpdating event and this works fine. However, if I add another record to the GridView, clicking on the edit button of that record gives a NullReference exception. If I then add another record, that 3rd record will go into edit mode. A 4th record will again fail with a NullReference exception and so on.
When debugging, it seems that on rows indexes 1,3,5 etc. the GridView doesn't go into edit mode however on row indexes 0, 2, 4 etc. the GridView will switch to edit mode.
This seems really strange behaviour. Any ideas what may be causing the GridView not to go into Edit mode on these rows?
A row's state can be one or a combination of the DataControlRowState values, so use bitwise operations to determine whether the state of the row includes a DataControlRowState value.
here
RowState contains more than one value (Alternate | Edit if you check RowState property during edit mode) using bit-logic.
Try
If (e.Row.RowState And DataControlRowState.Edit) > 0 Then
I got round this by amending the getDepartmentList function to return the Manager1 and Manager 2 fields then databinding them in the same was as I had bound 'Department'.
I then amended the RowDataBound event to the following:
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.RowState And DataControlRowState.Edit Then
Dim cbManager1 As DropDownList = TryCast(e.Row.FindControl("cbManager1"), DropDownList)
Dim cbManager2 As DropDownList = TryCast(e.Row.FindControl("cbManager2"), DropDownList)
Dim eHandler As EmployeeHandler = New EmployeeHandler
' Get the list of managers
Dim mgrs As New List(Of Manager)
mgrs = eHandler.GetManagerList
cbManager1.DataSource = mgrs
cbManager2.DataSource = mgrs
cbManager1.DataValueField = "Name"
cbManager1.DataTextField = "Name"
cbManager2.DataValueField = "Name"
cbManager2.DataValueField = "Name"
cbManager1.DataBind()
cbManager2.DataBind()
' Get the department name from the label in cell 0
Dim lbl As Label = e.Row.Cells(0).FindControl("lblDepartment")
Dim dept As Department = New Department
dept.Department = lbl.Text
' Pass the department name to the getManager1/2 functions to return the correct manager for that department
Dim mgr1 As Manager = eHandler.getManager1(dept)
Dim mgr2 As Manager = eHandler.getManager2(dept)
' Upper case the manager name to search the DDLs for item
Dim mgr1Name As String = mgr1.Name.ToUpper()
Dim mgr2Name As String = mgr2.Name.ToUpper()
' Find the manager in the DDL and select
cbManager1.SelectedValue = mgr1Name
cbManager2.SelectedValue = mgr2Name
End If
End If

Populate DropdownList based upon other DropDownList VB

I have found a couple of examples on the internet to do this but really struggling to get it working in VB. (Tried a converter but had mixed results)
I need the selection options of a Dropdownlist to be populated based upon the differing values in the first dropdown list.
Can anyone help with a releativley simple example in VB? Not fussed if the values are "hard coded" in the script. Or a SQL bit that pulls the data from a table
Thanks in advance!
The way it is done is to populate second dropdown in SelectedIndexChanged event of the first dropdown
Example:
Protected Sub ddlCountry_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim CountryID As Integer = Convert.ToInt32(ddlCountry.SelectedValue.ToString())
FillStates(CountryID)
End Sub
Private Sub FillStates(ByVal countryID As Integer)
Dim strConn As String = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ConnectionString
Dim con As New SqlConnection(strConn)
Dim cmd As New SqlCommand()
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = "Select StateID, State from State where CountryID =#CountryID"
cmd.Parameters.AddWithValue("#CountryID", countryID)
Dim objDs As New DataSet()
Dim dAdapter As New SqlDataAdapter()
dAdapter.SelectCommand = cmd
con.Open()
dAdapter.Fill(objDs)
con.Close()
If objDs.Tables(0).Rows.Count > 0 Then
ddlState.DataSource = objDs.Tables(0)
ddlState.DataTextField = "State"
ddlState.DataValueField = "StateID"
ddlState.DataBind()
ddlState.Items.Insert(0, "--Select--")
Else
lblMsg.Text = "No states found"
End If
End Sub
With html source as so:
<asp:DropDownList ID="ddlState" runat="server" AutoPostBack="True">
</asp:DropDownList>
<asp:DropDownList ID="ddlCountry" runat="server"
AutoPostBack="True" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged">
</asp:DropDownList>
You could accomplish this declaratively in the ASPX page like this:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:myConnString %>" SelectCommand="SELECT id, name FROM planets"></asp:SqlDataSource>
<asp:DropDownList ID="ddlPlanets" AutoPostBack="true" DataTextField="name" DataValueField="id" DataSourceID="SqlDataSource1" runat="server" AppendDataBoundItems="true" />
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:myConnString %>" SelectCommand="SELECT planetid, name FROM moons" FilterExpression="planetid = '{0}'">
<FilterParameters>
<asp:ControlParameter Name="planetid" ControlID="ddlPlanets" PropertyName="SelectedValue" />
</FilterParameters>
</asp:SqlDataSource>
<asp:DropDownList ID="ddlMoons" DataTextField="name" DataValueField="planetid" DataSourceID="SqlDataSource2" runat="server" />
Your best option will be to capture the SelectedIndexChanged event on the first dropdownlist, examine what the current value of that dropdownlist is, and then use that to clear and then populate the items in the second dropdownlist. When you do so, remember to set the AutoPostBack property of the first DropDownList to "true".

Resources