How I can access a control inside an ItemTemplate and connect it to a datasource by the time it is initialized? - asp.net

I know that there are similar questions to this one out there, but I can't seem to find any that address my issue.
I have a GridView that is populated with data from my database. The user has the option to delete or edit this data, a pretty standard operation. To insert data into the GridView, the user fills out a form and presses the submit button. In the form, there are three textboxes and a DropDownList. As you may expect, this means that, inside the GridView in edit mode, there are three textboxes and a DropDownList. My issue is this: When the user presses the Edit button, the application breaks. It says something to the effect of "myDropDownList cannot be loaded because the selected value is not in the list of items." Basically, the DropDownList inside the EditItemTemplate in the GridView is empty. I have tried to populate it the same way that I populate the other DropDownList (the one in the form), but it is not initialized until the GridView is put in edit mode. Here is the markup for the EditItemTemplate:
I have omitted some code for brevity.
<asp:TemplateField HeaderText="LocationCode" SortExpression="LocationCode">
<EditItemTemplate>
<asp:DropDownList ID="Ddl_EditLocCode" SelectedValue='<%# Bind("LocationCode") %>' runat="server"></asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvLocCode" runat="server" ErrorMessage="Location Code is a required field."
ControlToValidate="Ddl_EditLocCode" ForeColor="Red"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("LocationCode") %>' ID="Label5"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Here is the code I have written to populate the DropDownList inside the EditItemTemplate:
Note that this is the RowDataBound event handler.
Private Sub Gv_Assignments_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles Gv_Assignments.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If DataControlRowState.Edit Then
Dim editLocCodeDdl As DropDownList = DirectCast(e.Row.FindControl("Ddl_EditLocCode"), DropDownList)
CreateDataSourceForEditDdl(editLocCodeDdl)
End If
End If
End Sub
Protected Sub CreateDataSourceForEditDdl(editLocCodeDdl As DropDownList)
Try
Dim conn As New Connection
Dim DataReader As SqlDataReader
Dim listItem As New ListItem
Using conn.Conn
conn.Conn.Open()
Using cmd As New SqlCommand
With cmd
.Connection = conn.Conn
.CommandType = CommandType.Text
.CommandText = "SELECT [location_code], [loc_name] FROM [myTable] ORDER BY [location_code]"
End With
DataReader = cmd.ExecuteReader()
Dim locationCode As String
Dim loc_name As String
While DataReader.Read()
locationCode = DataReader.Item("location_code").ToString()
loc_name = DataReader.Item("loc_name").ToString()
editLocCodeDdl.Items.Add(New ListItem(locationCode & "-" & loc_name))
End While
End Using
End Using
Catch ex As Exception
End Try
End Sub
Perhaps the RowDataBound event handler is not where I should be attempting to populate the edit mode DropDownList... I'm not sure. Any help is greatly appreciated.
Edit: RowUpdating Code
Here is the RowUpdating code:
Private Sub Gv_Assignments_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles Gv_Assignments.RowUpdating
'change the lessonID to the appropriate ID based on the lesson name
'get the lesson name, then set the label text in the lesson ID column to the correct ID by calling GetLessonID(lessonname)
Dim lessonNameBox As DropDownList = DirectCast(Gv_Assignments.Rows(e.RowIndex).FindControl("ddlEditLessonName"), DropDownList)
'Dim lessonIdLabel As Label = DirectCast(Gv_Assignments.Rows(e.RowIndex).FindControl("LblLessonID"), Label)
'Dim ID As Integer = Integer.Parse(Gv_Assignments.Rows(e.RowIndex).Cells(1).Text)
'lessonIdLabel.Text = GetLessonID(lessonNameBox.SelectedValue)
Gv_Assignments.Rows(e.RowIndex).Cells(3).Text = GetLessonID(lessonNameBox.SelectedValue)
'UpdateLessonID(lessonIdLabel.Text, ID)
End Sub
As you can see, I am doing pretty much nothing in this function. I should add that I used the GridView's smart tag to assign a SqlDataSource to the GridView. Every other editable cell gets successfully updated when I edit it in edit mode. For some reason, when I removed this line: SelectedValue='<%# Bind("LocationCode") %>', the Ddl_EditLocCode successfully populated with the desired values, but it failed to update on the back end and front end when I edited it; in fact, it made the value Null. Any ideas?
Edit 2: The SqlDataSource
<asp:SqlDataSource ID="sds_GvAssignments" runat="server" ConnectionString='<%$ ConnectionStrings:DedicatedTerminal_devConnectionString %>'
DeleteCommand="DELETE FROM [CreatedAssignments] WHERE [ID] = #ID"
InsertCommand="INSERT INTO [CreatedAssignments] ([LessonName], [LessonID], [StartDate], [EndDate], [LocationCode],
[DateAssigned]) VALUES (#LessonName, #LessonID, #StartDate, #EndDate, #LocationCode, #DateAssigned)"
SelectCommand="SELECT [ID], [LessonName], [LessonID], [StartDate], [EndDate], [LocationCode], [DateAssigned]
FROM [CreatedAssignments]" UpdateCommand="UPDATE [CreatedAssignments] SET [LessonName] = #LessonName,
[LessonID] = #LessonID, [StartDate] = #StartDate, [EndDate] = #EndDate, [LocationCode] = #LocationCode,
[DateAssigned] = #DateAssigned WHERE [ID] = #ID">
<DeleteParameters>
<asp:Parameter Name="ID" Type="Int32"></asp:Parameter>
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="LessonName" Type="String"></asp:Parameter>
<asp:Parameter Name="LessonID" Type="String"></asp:Parameter>
<asp:Parameter DbType="Date" Name="StartDate"></asp:Parameter>
<asp:Parameter DbType="Date" Name="EndDate"></asp:Parameter>
<asp:Parameter Name="LocationCode" Type="String"></asp:Parameter>
<asp:Parameter Name="DateAssigned" Type="DateTime"></asp:Parameter>
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="LessonName" Type="String"></asp:Parameter>
<asp:Parameter Name="LessonID" Type="String"></asp:Parameter>
<asp:Parameter DbType="Date" Name="StartDate"></asp:Parameter>
<asp:Parameter DbType="Date" Name="EndDate"></asp:Parameter>
<asp:Parameter Name="LocationCode" Type="String"></asp:Parameter>
<asp:Parameter Name="DateAssigned" Type="DateTime"></asp:Parameter>
<asp:Parameter Name="ID" Type="Int32"></asp:Parameter>
</UpdateParameters>
</asp:SqlDataSource>

The code to fill the DropDownList seems ok at first glance. First try removing SelectedValue='<%# Bind("LocationCode") %>'. The error means that the value of LocationCode does not exist in the ListItems of Ddl_EditLocCode.
And that would seem to make sense since you are adding a ListItem with a value of both the locationCode AND loc_name (New ListItem(locationCode & "-" & loc_name)), therefore only the value of LocationCode does not exist and throws the error.
The solution is to create a ListItem with both a Text and Value specified.
New ListItem(locationCode & "-" & loc_name, locationCode, true)

Related

How I do DirectCast on Wizard Control to sql?

I try using wizard control, I've 5 step on my wizard. I want to store my data when user clik finish button but I've some problem with store the data into sql. Here my code :
<asp:SqlDataSource ID="Wizard1SDS"
runat="server"
ConnectionString="<%$ ConnectionStrings:tr9DbConn %>"
InsertCommand = "INSERT INTO [tr9_detail_eval] ([response_text]) VALUES (#txb_answer1)">
<InsertParameters>
<asp:ControlParameter Name="txb_answer1" Type="String" ControlID="txb_answer1" PropertyName="Text"/>
</InsertParameters>
</asp:SqlDataSource>
my code behind :
Protected Sub Wizard1_FinishButtonClick(sender As Object, e As WizardNavigationEventArgs) Handles Wizard1.FinishButtonClick
Dim Wizard1SDS As SqlDataSource = DirectCast(Me.Wizard1.WizardSteps(0).FindControl("Wizard1SDS"), SqlDataSource)
Wizard1SDS.Insert()
End Sub
my textbox code on wizard :
<div style="margin : 10px;">
<asp:TextBox runat="server" ID="txb_answer1" TextMode="MultiLine" Columns="10" Rows="50" Height="123px" Width="600px" CssClass="step1" />
</div>
Error image
Any suggestion ? Thank You,
I've solve my problem with this code behind, I replace DirectCast become CType and cast the textbox to string then findcontrol textbox. Here's my code :
Protected Sub Wizard1_FinishButtonClick(sender As Object, e As WizardNavigationEventArgs) Handles Wizard1.FinishButtonClick
Dim txb_answer1 As String = CType(Me.Wizard1.WizardSteps(0).FindControl("txb_answer1"), TextBox).Text
Wizard1SDS.Insert()
Response.Redirect("Eval.aspx")
End Sub

I am having trouble getting my listbox to populate with the output from a sql query

I can’t seem to figure out where I went wrong here. I have two list boxes the first pulls its data from a stored procedure on a sql server. the second list box is supposed to populate when the an item in the first list box is selected. the second list box’s stored procedure should be passed the text of the selected item when that item in the first list box has been clicked. the problem is that that second list box is not populating. I would appreciate any helpful feedback or possibly an easier way of getting done what I am trying to do.
ASP.NET:
<asp:ListBox ID="ListBox1" runat="server" DataSourceID="LOCATION" DataTextField="L_Name" DataValueField="L_Name" AutoPostBack="True"></asp:ListBox>
<asp:SqlDataSource ID="LOCATION" runat="server" ConnectionString="<%$ ConnectionStrings:SAMC_2ConnectionString %>" SelectCommand="L_Get" SelectCommandType="StoredProcedure"></asp:SqlDataSource>
<asp:ListBox ID="ListBox2" runat="server" Height="150px" Width="200px" AutoPostBack="True" DataTextField="C_Name" DataValueField="C_Name" />
<asp:SqlDataSource ID="CompByLocal" runat="server" ConnectionString="<%$ ConnectionStrings:SAMC_2ConnectionString %>" SelectCommand="L_Get_C" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="ListBox1" DefaultValue="" Name="L_Name" PropertyName="SelectedValue" Type="String" />
<asp:Parameter Name="L_ID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
VB.NET:
Protected Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Dim val As String = ListBox1.Items(ListBox1.SelectedIndex).ToString
TextBox1.Text = val
ListBox2.Items.Clear()
ListBox2.DataSource = CompByLocal
ListBox2.DataBind()
End Sub
My advice would be ditch the SqlDataSources and do it all in the back end - you can then be a lot more precise about when things occur in my experience. Ive done my best to write the necessary code below however my native tongue is C# - Ive used an online converter so please forgive any minor syntax errors.
ASPX:
<asp:ListBox ID="ListBox1" runat="server" DataTextField="L_Name" DataValueField="L_Name" AutoPostBack="True"></asp:ListBox>
<asp:ListBox ID="ListBox2" runat="server" Height="150px" Width="200px" AutoPostBack="True" DataTextField="C_Name" DataValueField="C_Name" />
.VB
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
if (IsPostback) return
Dim results As New DataTable()
Using connection As New SqlConnection(ConfigurationManager.ConnectionStrings("SAMC_2ConnectionString "))
connection.Open()
Using command As New SqlCommand("L_Get", connection)
command.CommandType = CommandType.StoredProcedure
results.Load(command.ExecuteReader())
End Using
End Using
ListBox1.DataSource = results;
ListBox1.DataBind();
End Sub
Protected Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim results As New DataTable()
Using connection As New SqlConnection(ConfigurationManager.ConnectionStrings("SAMC_2ConnectionString "))
connection.Open()
Using command As New SqlCommand("L_Get_C", connection)
command.CommandType = CommandType.StoredProcedure
command.Parameters.AddWithValue("L_ID",ListBox1.SelectedValue)
results.Load(command.ExecuteReader())
End Using
End Using
ListBox2.DataSource = results
ListBox2.DataBind()
End Sub

Double Databinding Cascading DropDownList to two SqlDataSources in a FormView

I have two cascading dropdown lists I'm attempting to bind to two separate SqlDataSources each.
These dropdownlists exist in a FormView's EditItemTemplate. Inside the EditItemTemplate two sqldatasource controls exist that populate the department and the jobname. The DeptID and the JobID are the primary keys in those tables. This creates the "cascading effect" between departments and jobs. When a department is selected, only the jobs associated with that department appear.
This piece is working properly.
<asp:FormView ID="frmProfile" runat="server" DataSourceID="sqlDSProfile"
DataKeyNames="EUID" style="margin-top: 0px">
<EditItemTemplate>
<asp:DropDownList ID="ddlDepartments" runat="server" Width="135px"
DataSourceID="sqlDSDepartments"
DataTextField="Department"
DataValueField="DeptID" AutoPostBack="True"
SelectedValue='<%# Bind("CurrentDeptID") %>'
AppendDataBoundItems="true" >
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlJobNames" runat="server" Width="185px"
DataSourceID="sqlDSJobs" DataTextField="JobName" DataValueField="JobID"
SelectedValue='<%# Bind("CurrentJobID") %>'
AppendDataBoundItems="true" >
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="sqlDSDepartments" runat="server"
ConnectionString="<%$ ConnectionStrings:JobsDB %>"
SelectCommand="SELECT tblDepartments.DeptID,
tblDepartments.Department
FROM tblDepartments" />
<asp:SqlDataSource ID="sqlDSJobs" runat="server"
ConnectionString="<%$ ConnectionStrings:JobsDB %>"
SelectCommand="SELECT tblJobs.JobID, tblJobs.JobName FROM tblJobs
INNER JOIN tblDeptsJobs ON tblDeptsJobs.JobID = tblJobs.JobID
WHERE tblDeptsJobs.DeptID = #DeptID" >
<SelectParameters>
<asp:ControlParameter ControlID="ddlDepartments" Name="DeptID"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
</EditItemTemplate>
</asp:FormView>
Outside the formview the SqlDataSource exists that binds all of the information to the Employee table in an update statement. I'm leaving all of the other information in this SqlDataSource even though it's been omitted from the FormView above.
<asp:SqlDataSource ID="sqlDSProfile" runat="server"
ConnectionString="<%$ ConnectionStrings:JobsDB %>"
SelectCommand="SELECT tblEmployee.EUID,
tblEmployee.DateHired,
tblEmployee.LastName,
tblEmployee.HiredLastName,
tblEmployee.FirstName,
tblEmployee.Role,
tblEmployee.JobGrade,
tblEmployee.CurrentDeptID,
tblDepartments.Department,
tblDepartments.DeptID,
tblEmployee.CurrentJobID,
tblJobs.JobName,
tblJobs.JobID,
tblEmployee.CurrentShift,
tblEmployee.JobDate,
tblEmployee.IsDisplaced,
tblEmployee.EligibilityDate
FROM tblEmployee
LEFT OUTER JOIN tblDepartments ON tblEmployee.CurrentDeptID = tblDepartments.DeptID
EFT OUTER JOIN tblJobs ON tblEmployee.CurrentJobID = tblJobs.JobID
WHERE (tblEmployee.EUID = #EUID)"
UpdateCommand="UPDATE [tblEmployee]
SET [tblEmployee].[DateHired] = #DateHired,
[tblEmployee].[LastName] = #LastName,
[tblEmployee].[HiredLastName] = #HiredLastName,
[tblEmployee].[FirstName] = #FirstName,
[tblEmployee].[Role] = #Role,
[tblEmployee].[JobGrade] = #JobGrade,
[tblEmployee].[CurrentDeptID] = #CurrentDeptID,
[tblEmployee].[CurrentJobID] = #CurrentJobID,
[tblEmployee].[CurrentShift] = #CurrentShift,
[tblEmployee].[JobDate] = #JobDate,
[tblEmployee].[IsDisplaced] = #IsDisplaced,
[tblEmployee].[EligibilityDate] = #EligibilityDate
WHERE [tblEmployee].[EUID] = #EUID"
ProviderName="System.Data.SqlClient">
<SelectParameters>
<asp:SessionParameter Name="EUID" SessionField="sProfileEUID" DbType="String" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="DateHired" DbType="Date" />
<asp:Parameter Name="LastName" DbType="String" />
<asp:Parameter Name="HiredLastName" DbType="String" />
<asp:Parameter Name="FirstName" DbType="String" />
<asp:Parameter Name="Role" DbType="String" />
<asp:Parameter Name="JobGrade" DbType="Byte" />
<asp:Parameter Name="CurrentDeptID" DbType="Int32" />
<asp:Parameter Name="CurrentJobID" DbType="Int32" />
<asp:Parameter Name="CurrentShift" DbType="Int32" />
<asp:Parameter Name="JobDate" DbType="Date" />
<asp:Parameter Name="IsDisplaced" DbType="Boolean"/>
<asp:Parameter Name="EligibilityDate" DbType="Date"/>
<asp:SessionParameter Name="EUID" SessionField="sProfileEUID" DbType="String" />
</UpdateParameters>
</asp:SqlDataSource>
The only pieces I can't figure out how to bind are the Departments and the Jobs. Everything else is working. I've tried using the following code in the DropDownList controls...
SelectedValue='<%# Bind("CurrentDeptID") %>'
SelectedValue='<%# Bind("CurrentJobID") %>'
...but these result in errors.
Summary
When the user clicks edit, I need the values in the two dropdownboxes to pull their selectedvalue from the main sqlDSProfile data source, but I need them to be updatable. I've gotten it to the point where I can update and bind the job that an associate belongs to, but because the dropdownlists cascade, when I attempt to change the department the AutoPostBack breaks the binding between sqlDSProfile - CurrentJobID and ddlJobs.
Update
I added tblEmployee.CurrentDeptID and tblEmployee.CurrentJobID to the select statement, and added Bind() statements to the DropDownList controls.
SelectedValue='<%# Bind("CurrentDeptID") %>'
SelectedValue='<%# Bind("CurrentJobID") %>'
The two DropDownLists are now populated with accurate information pulled from the Employee table, showing the department and job that the employee belongs to.
The two DropDownLists are also populated by the two SqlDataSources inside the FormView, giving me options for changing the department and changing the job.
When I change the Job, it works and the employees job is updated.
When I change the Department, it breaks saying DataBinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
Close to Done
I removed the data binding from ddlJobs and coded that in the background.
Protected Sub frmProfile_ItemUpdating(sender As Object, e As System.Web.UI.WebControls.FormViewUpdateEventArgs) Handles frmProfile.ItemUpdating
If frmProfile.CurrentMode = FormViewMode.Edit Then
e.NewValues("CurrentJobID") = DirectCast(DirectCast(sender, FormView).FindControl("ddlJobs"), DropDownList).SelectedValue
End If
End Sub
The only piece that's left is building the code for when the ddlDepartments changes.
pseudocode...
' If Item exists in ddlJobs Then
' select item (CurrentJobID)
' else
' select index 0 and make them pick something new
' end if
So Close!
Updated Again
This is the code I've developed to loosely bind this. In the page_load I'm trying to pull the contents of CurrentJobID from sqlDSProfile and check to see if that value exists in ddlJobs. If it does I want to set ddlJobs.SelectedValue = to that CurrentJobID. If it doesn't I want to set the selectedindex to 0 which is a message saying "pick one" or something.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If frmProfile.CurrentMode = FormViewMode.Edit Then
' Need to determine if the CurrentJobID returned in the select statement
' exists in the ddlJobs dropdownlist. If it does, set that to the
' selectedvalue, if not set it to 0 so the user can select a new job.
Dim ddlJobs As DropDownList = frmProfile.FindControl("ddlJobs")
Dim dvProfile As DataView = sqlDSProfile.Select(DataSourceSelectArguments.Empty)
Dim drvProfile As DataRowView = dvProfile(0)
If ddlJobs.Items.FindByValue(drvProfile("CurrentJobID")) Is DBNull.Value Then
ddlJobs.SelectedIndex = 0
Else
ddlJobs.SelectedValue = drvProfile("CurrentJobID")
End If
End If
End Sub
Its returning a null reference exception on the line where I'm checking for dbnull.value
I had a similar issue and found a very simple resolution, (and in c#). Imagine a database with a table Questions, related to category and subcategory tables (which are also related and constrained). When trying to update existing records asp throws an error. This is the solution that I worked out thanks to the information above from Lucretius et al.
Only databind the parent dropdownlist
Find a way to insert the child dropdown selected value on the update event of the datasource.
As:
protected void odseditquestion_Updating(object sender, ObjectDataSourceMethodEventArgs e)
{
//dynamically assign value from ddlsubcategory to odseditquestion on updating event
//you really should not have to do this
DropDownList ddlsubcategory = (DropDownList)fveditquestion.FindControl("ddlsubcategory");
e.InputParameters["subcatid"] = (ddlsubcategory.SelectedValue);
}
It works on my application. Hope it helps somebody, this one cost me half a day, such is asp!!
The problem can be if tlbEmployee columns in the SqlDSProfile in the update statement and field names used by your controls do not match. Other procedures you've followed are right.
SqlDataSource control expects field names it updates to be similar
with those bound to the controls(fields) inside the DataBound control.
The Solution can be: change all the update Parameters to ControlParameters referencing the right control for each one
Update: Wait, I think the problem is your select statement of the SqlDSProfile should contain: CurrentDeptID and CurrentJobID. Try it:
<asp:SqlDataSource ID="sqlDSProfile" runat="server"
ConnectionString="<%$ ConnectionStrings:JobsDB %>"
SelectCommand="SELECT tblEmployee.EUID,
tblEmployee.DateHired,
tblEmployee.LastName,
tblEmployee.HiredLastName,
tblEmployee.FirstName,
tblEmployee.Role,
tblEmployee.JobGrade,
tblDepartments.Department,
tblJobs.JobName,
tblEmployee.CurrentShift,
tblEmployee.JobDate,
tblEmployee.IsDisplaced,
tblEmployee.EligibilityDate
tblEmployee.CurrentDeptID,
tblEmployee.CurrentJobID
FROM tblEmployee
Advice: Test your code portion by portion.
Try the code without the dropdownlist, Test separately
Add the one drop downlist
Use select * from ... in select queries
Avoid ajax when testing
If you make it
Add portions of code portion after portion
at last use the partial updating (ajax)
I have a working solution now, thanks in part to Nuux and a bunch of online research. The tip about the join statement wasn't relevant, but the tip about including "CurrentJobID" and "CurrentDeptID" in my select query was spot on.
In addition to that I had to rework the controls a little. The two cascading dropdownlists are below. The ddlJobs dropdown list behaves like a normal databound control, but it doesn't have the Bind("CurrentJobID") statement I was trying in my original post.
<asp:DropDownList ID="ddlDepartments" runat="server" Width="185px"
DataSourceID="sqlDSDepartments"
DataTextField="Department"
DataValueField="DeptID"
SelectedValue='<%# Bind("CurrentDeptID") %>'
AppendDataBoundItems="true"
AutoPostBack="True" >
<asp:ListItem Text="--Select One--" Value="" />
</asp:DropDownList>
<asp:DropDownList ID="ddlJobs" runat="server" Width="185px"
DataSourceID="sqlDSJobs"
DataTextField="JobName"
DataValueField="JobID"
AppendDataBoundItems="true"
OnDataBinding="ddlJobs_DataBinding" />
The only thing the custom routine "ddlJobs_DataBinding" is doing is adding "--Select One--" as index 0 in the ddlJobs dropdown. I tried this in several places, like page_load, and the databound event of the formview with no success.
Protected Sub ddlJobs_DataBinding(sender As Object, e As System.EventArgs)
Dim ddlJobs As DropDownList = frmProfile.FindControl("ddlJobs")
Dim liSelectOne As New ListItem("--Select One--", 0)
ddlJobs.Items.Clear()
ddlJobs.Items.Insert(0, liSelectOne)
End Sub
The databound event of the formview frmProfile_DataBound event does do some work though. When the user clicks "edit" on the formview to enter editing mode this ensures that the dropdownlist ddlJobs has the correct job selected by default for the profile in question. If the user hasn't been assigned to a job then it defaults to selectedindex 0 which is "--Select One--" set in custom databinding event just above.
Protected Sub frmProfile_DataBound(sender As Object, e As System.EventArgs) Handles frmProfile.DataBound
If frmProfile.CurrentMode = FormViewMode.Edit Then
Dim ddlJobs As DropDownList = frmProfile.FindControl("ddlJobs")
Dim dvProfile As DataView = sqlDSProfile.Select(DataSourceSelectArguments.Empty)
Dim drProfile As DataRow = dvProfile.Table.Rows(0)
If drProfile("CurrentJobID").ToString() = "" Then
ddlJobs.SelectedIndex = 0
Else
ddlJobs.SelectedValue = drProfile("CurrentJobID").ToString()
End If
End If
End Sub
Finally, if the user selects a new job from ddlJobs, that value has to be fed to the database, which the ItemUpdating event of the formview handles.
Protected Sub frmProfile_ItemUpdating(sender As Object, e As System.Web.UI.WebControls.FormViewUpdateEventArgs) Handles frmProfile.ItemUpdating
If frmProfile.CurrentMode = FormViewMode.Edit Then
Dim ddlJobs As DropDownList = frmProfile.FindControl("ddlJobs")
e.NewValues("CurrentJobID") = ddlJobs.SelectedValue
End If
End Sub
Done!

how to obtain the value of label in edititemplate (of formview) to the code behind file?

I'm trying to bring the value of text entered in the label "telephoneidLabel" to my code behind file to set value in the where clause of my sqlcommand object.
how do i do it?
the edititemtemplate is within the formview.
<EditItemTemplate >
telephoneid:
<asp:Label ID = "telephoneidLabel" runat="server" Text='<%# Bind ("telephoneid")%>' />
once you catch the correct item you can use the FindControl method of the Item, something like this:
var myLabel = item.FindControl("telephoneidLabel") as Label;
if(myLabel != null)
{
var myText = myLabel.Text;
}
the way you get the item object depends on how your code is, if you do a loop on the whole formview control or you get the editItem or the selectedItem etc... but FindControl and its usage is always the same.
Assuming that the row is in edit mode, you should be able to get the value from the control like this:
//the row that's being edited
GridViewRow row = GridView1.Rows[0];
if (row.RowState == DataControlRowState.Edit)
{
Label lblCtrl = row.FindControl("Label1") as Label;
if (lblCtrl != null)
{
string text = lblCtrl.Text;
}
}
I'm wondering if it might be better to use a datakey for this, though:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="SomeColumn" ...>
Code-behind:
string someValue = (string)GridView1.DataKeys[0]["SomeColumn"];
This is pretty easy to do - now the two way binding should automatically do this for you, assuming that on the SqlDataSource that you use as the data source for you GridView. Here's some code I have on the SqlDataSource:
UpdateCommand="UPDATE [prov] SET provname=#provname, addr=#addr, tele=#tele WHERE provID=#provID " >
<UpdateParameters>
<asp:ControlParameter ControlID="dgProviders" Name="provID" PropertyName="SelectedValue" />
<asp:Parameter Name="login" />
<asp:Parameter Name="password" />
<asp:Parameter Name="username" />
<asp:Parameter Name="contact_email" />
<asp:Parameter Name="bar_number" />
</UpdateParameters>
Now, if you want to get to the label object, then in an approproate event handler, you can use the following code as an example:
Protected Sub dgProviders_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles dgProviders.RowCommand
Select e.CommandName
Case "Search"
Dim strProvName As String = CType(Me.dgProviders.HeaderRow.FindControl("txtSearchName"), TextBox).Text
If strProvName = String.Empty Then
Me.lblResults.Text = "<span style=""color:maroon"">You have to enter a search term: part of the name to do a search.</span><br />"
Else
Me.sqlProvList.SelectParameters.Clear()
If strProvName <> String.Empty Then
Me.sqlProvList.SelectCommand = "SELECT provID, provname, addr, tele FROM prov WHERE [provname] LIKE '%' + #username + '%' ORDER BY [provname]"
Me.sqlProvList.SelectParameters.Add("username", DbType.String, strProvName)
End If
Me.dgProviders.PageIndex = 0
Session("Select") = Me.sqlProvList.SelectCommand
End If
End Select
End Sub
This is from a "search" button that I have, getting values from text boxes in the header row of the data grid.

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