Change textbox value when selecting dropdownlist value - asp.net

I have a dropdownlist control that shows the primary key from a table called model, and a textbox that should show another value(a foreign key) from that same table when I use the dropdownlist.
Both PK and FK have a single value.
Since I didn't have a clue how to do this, I used a search method that should be called everytime someone selects a new value from the dropdownlist.
Search code:
Public Function searchArea(ByVal model As String) As String
Dim mycon As New Connection
Using connection As New SqlConnection(mycon.GetConnectionString())
Using command As New SqlCommand()
command.Connection = connection
command.CommandType = CommandType.Text
command.CommandText = "SELECT area FROM model WHERE model= #model"
command.Parameters.AddWithValue("#model", model)
connection.Open()
Dim dataReader As SqlDataReader = command.ExecuteReader()
If (dataReader.Read()) Then
Return dataReader.ToString(0)'this query should always have a single value
End If
Return "Nothing"
End Using
End Using
End Function
Event code:
Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles DropDownList1.SelectedIndexChanged
Dim objModel As New ModelDAO 'the class where the method is
TextBox9.Text = objModel.searchArea(DropDownList1.Text)
End Sub
.
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True"
DataSourceID="SqlDataSource1" DataTextField="MODEL" DataValueField="MODEL">
<asp:ListItem Text="-Select-" Value="" />
</asp:DropDownList>
<asp:TextBox ID="TextBox9" runat="server" Enabled="False" Height="24px"
Width="219px"></asp:TextBox>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DBUserInterfaceConnectionString %>"
SelectCommand="SELECT [MODEL] FROM [MODEL]">
</asp:SqlDataSource>
But as I thought, it doesn't work, can you help me please?
EDIT: Thanks, now it triggers, but I'm getting the value: 'S' that value doesn't belong to my table.Can you tell me if my search method is ok?

Try to add this
<asp:DropDownList ID="DropDownList1"
runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
.....
</asp:DropDownList>

Try to Load datareader into datatable and than use it to print data into the textbox..

Thank you everyone, I solved it with this:
Return dataReader.GetString(0)
instead of:
Return dataReader.ToString(0)
It was just a type conversion problem.

Related

Why is an item not getting selected in Dropdownlist OnRowDataBound event?

In the OnRowDataBoundevent of the ASP.Net GridView I am trying to populate the Department DropDownList (ddlDepts) which will be displayed when a row is edited.
The code below is not working as the DropdownList is empty.
Any ideas what I am doing wrong?
'//GridView markup:
<asp:TemplateField HeaderText="Department" ItemStyle-Width = "150">
<ItemTemplate>
<asp:Label ID = "lblDept" runat="server" Text='<%# Eval("deptName")%>'></asp:Label>
<asp:DropDownList ID="ddlDepts" runat="server" Visible = "false">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
''//Codefile
Protected Sub OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim cmd As New SqlCommand("SELECT DISTINCT(DeptID,DeptName) FROM Departments")
Dim ddlDepts As DropDownList = TryCast(e.Row.FindControl("ddlDepts"), DropDownList)
ddlDepts.DataSource = Me.ExecuteQuery(cmd, "SELECT")
ddlDepts.DataTextField = "DeptID"
ddlDepts.DataValueField = "DeptName"
ddlDepts.DataBind()
Dim DeptName As ListItem = ddlDepts.Items.FindByValue("lblDept")
If DeptName IsNot Nothing Then
ddlDepts.SelectedValue = DeptName.Value
End If
End If
End Sub
Not sure which SQL you are using, but I think the query may be incorrect.
In MS SQL you would use it like this:
SELECT DISTINCT DeptID, DeptName FROM Departments
And I have no knowledge of MySQL (or other databases), but a quick search seems to indicate it uses the same methods for distinct.

How to bind DropDownList in Gridview with data NOT from gridview

Half the battle of getting an answer is knowing how to ask the question. I am not certain I am doing a good job of that but this is my best shot.
I'm trying to bind a ddl with data inside a gridview that is NOT coming from the gridview itself. This is within the EditItemTemplate. The purpose for doing so is to give the user, to start, a selected value and a series of other values from a lookup stored procedure.
I'll mention here that I have done this successfully before but using an ObjectDataSource. I am trying to avoid that this time and do it entirely from the code behind for now then move it to a data layer later.
Here is what I have so far...
<asp:GridView ID="usersGrid" runat="server"
DataKeyNames="userID"
AutoGenerateColumns="false" Width="580"
OnRowUpdating="usersGrid_RowUpdating"
OnRowEditing="usersGrid_RowEditing"
OnRowCancelingEdit="usersGrid_RowCancelingEdit" OnRowDeleting="usersGrid_RowDeleting"
>
...
<EditItemTemplate>
<div class="gridName">
<asp:TextBox ID="txtFirstName" Text='<%#Eval("firstName") %>' runat="server" Width="95" />
</div>
<div class="gridName">
<asp:TextBox ID="txtLastName" Text='<%#Eval("lastName") %>' runat="server" Width="95" />
</div>
<div class="gridEmail">
<asp:TextBox ID="txtEmail" Text='<%#Eval("email") %>' runat="server" Width="245" />
</div>
<div class="gridName">
<asp:DropDownList ID="ddl_GetLists"
DataSourceID="GetListData()"
AppendDataBoundItems="true"
DataValueField="listID"
DataTextField="listName"
SelectedValue='<%#Bind("listID") %>'
runat="server"
>
</asp:DropDownList>
</div>
</EditItemTemplate>
....
Protected Sub usersGrid_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
usersGrid.EditIndex = e.NewEditIndex
BindData()
End Sub
....
Private Sub BindData()
Dim conn As New SqlConnection(connectionString)
Dim ad As New SqlDataAdapter("MAINT_DIST_GET_USERS", conn)
Dim ds As New DataSet()
ad.Fill(ds)
GetListData()
usersGrid.DataSource = ds
usersGrid.DataBind()
End Sub
I'm including last two as well as other approaches I've tried and failed.
...
Protected Sub usersGrid_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowState = DataControlRowState.Edit Then
Dim ddl As DropDownList = DirectCast(e.Row.FindControl("ddl_GetLists"), DropDownList)
Dim conn As New SqlConnection(connectionString)
Dim ad As New SqlDataAdapter("MAINT_DIST_GET_LISTS", conn)
Dim ds As New DataSet()
ad.Fill(ds)
ddl.DataSource = ds
ddl.DataBind()
End If
End Sub
Public Function BindDropdown() As DataSet
Dim conn As New SqlConnection(connectionString)
Dim ad As New SqlDataAdapter("MAINT_DIST_GET_LISTS", conn)
Dim ds As New DataSet()
ad.Fill(ds)
ddl_GetLists.DataSource = ds
ddl_GetLists.DataBind()
End Function
I'll also ask why, in the final function, why is the control, ddl_GetLists, not recognized as well? Inside the grid it disappears from the designer but outside of the grid it reappears.
Thank you all for your help.
You have a couple of options. You can use a datasource control, or you can bind the dropdowns in code-behind in the RowDataBound event of the GridView.
I noticed a couple of issues in your code too. In your example you're assigning the DataSourceID incorrectly. The DataSourceID should point to the ID of a datasource control on the page:
<asp:DropDownList ID="ddl_GetLists"
DataSourceID="SqlDataSource1"
AppendDataBoundItems="true"
DataValueField="listID"
DataTextField="listName"
SelectedValue='<%#Bind("listID") %>'
runat="server">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT listID, listName FROM SomeTable">
</asp:SqlDataSource>
If you want to do the binding in code-behind, you can do this through the RowDataBound event:
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow AndAlso (e.Row.RowState And DataControlRowState.Edit) = DataControlRowState.Edit Then
Dim ddl As DropDownList = TryCast(e.Row.FindControl("ddl_GetLists"), DropDownList)
If ddl IsNot Nothing Then
ddl.DataSource = RetrieveDataSource()
ddl.DataBind()
End If
End If
End Sub
You can simply create a global list of type that you want and set it as null
if you are using linq then just put that source in the DropDownListObject.DataSource
DropDownListObject.DataSource=ObjListSource;
DropDownListObject.DataBind;
Hope it will be helpful.
I see a couple issues.
Protected Sub usersGrid_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
usersGrid.EditIndex = e.NewEditIndex
BindData()
End Sub
Why are you doing this? Why would you bind the grid again on an event on your grid thats already been filled?
You fix this:
In the code page, you define a GetListData() public function (i think you did).
Use DataSource property (if you want to call a function) :
<asp:DropDownList ID="ddl_GetLists"
DataSource='<%# GetListData() %>'
AppendDataBoundItems="true"
DataValueField="listID"
DataTextField="listName"
SelectedValue='<%#Bind("listID") %>'
runat="server" >
</asp:DropDownList>

How to Make Boolean Column Editable (asp.net VB gridView filled by DataTable that has Boolean Column) ?

After Filling a DataTable in GridView's DataSource . A column with check box Type appears but it created as read only column
and I can't enable it or make it editable... even i tried .readonly = false
and still can't be edited
can any one help please ?
you can try like this..
This is by design; rows in a GridView are not editable by default.
There's two ways you might address this:
Add an Edit link
In your GridView tag, add AutoGenerateEditButton="True". When your GridView renders in the browser, you should now find a hyperlink labelled 'Edit'. If you click it, the fields in your GridView will become editable, and the Edit link will become two links, one to save your changes to the database and the other to discard them. Using this method, all the plumbing to wire up changes in the GridView to the database can be done for you, depending on how you're doing the databinding. This example uses a SqlDataSource control.
(source: philippursglove.com)
Add a TemplateField with a CheckBox inside it
Inside the <columns> tag, you can add TemplateFields that you set the databinding up for yourself e.g.
<asp:TemplateField HeaderText="Discontinued">
<ItemTemplate>
<asp:CheckBox runat="server" ID="DiscontinuedCheckBox" Checked="<%# Eval("Discontinued") %>" AutoPostback="true" OnCheckedChanged="DiscontinuedCheckBox_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
(source: philippursglove.com)
This checkbox will be enabled, but you need to do the work yourself to reflect any changes back to the database. This is straightforward as long as you can get a database key, as you'll need to run an UPDATE statement at some point and you want to run it on the right row! Here's two ways you could do this:
In your Gridview tag, add DataKeyNames="MyDatabasePrimaryKey". Then in your CheckedChanged event handler, you need to find out which row you are in and look that up in the DataKeys array.
Protected Sub DiscontinuedCheckBox_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim DiscontinuedCheckBox As CheckBox
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim productId As Integer
Dim selectedRow As GridViewRow
' Cast the sender object to a CheckBox
DiscontinuedCheckBox = CType(sender,CheckBox)
' We can find the row we clicked the checkbox in by walking up the control tree
selectedRow = CType(DiscontinuedCheckBox.Parent.Parent,GridViewRow)
' GridViewRow has a DataItemIndex property which we can use to look up the DataKeys array
productId = CType(ProductGridView.DataKeys(selectedRow.DataItemIndex).Value,Integer)
conn = New SqlConnection(ProductDataSource.ConnectionString)
cmd = New SqlCommand
cmd.Connection = conn
cmd.CommandType = CommandType.Text
If DiscontinuedCheckBox.Checked Then
cmd.CommandText = ("UPDATE Products SET Discontinued = 1 WHERE ProductId = " + ProductId.ToString)
Else
cmd.CommandText = ("UPDATE Products SET Discontinued = 0 WHERE ProductId = " + ProductId.ToString)
End If
conn.Open
cmd.ExecuteNonQuery
conn.Close
End Sub
Or, you could add the key in a HiddenField control:
<asp:TemplateField HeaderText="Discontinued">
<ItemTemplate>
<asp:hiddenfield runat="server" id="ProductIdHiddenField" Value='<%# Eval("ProductID") %>' />
<asp:CheckBox runat="server" ID="DiscontinuedCheckBox" Checked="<%# Eval("Discontinued") %>" AutoPostback="true" OnCheckedChanged="DiscontinuedCheckBox_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
Protected Sub DiscontinuedCheckBox_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim DiscontinuedCheckBox As CheckBox
Dim ProductIdHiddenField As HiddenField
DiscontinuedCheckBox = CType(sender,CheckBox)
ProductIdHiddenField = CType(DiscontinuedCheckBox.Parent.FindControl("ProductIdHiddenField"),HiddenField)
conn = New SqlConnection(ProductDataSource.ConnectionString)
..................
If DiscontinuedCheckBox.Checked Then
cmd.CommandText = ("UPDATE Products SET Discontinued = 1 WHERE ProductId = " + ProductIdHiddenField.Value)
End If
...............
End Sub
i hope it will helps you....

Checkboxes in usercontrol won't check although they say they are

I have a simple usercontrol, with a datalist, and checkboxes inside.
<asp:DataList ID="DataListDroits" runat="server" DataKeyField="droit_id" DataSourceID="SqlDroits">
<ItemTemplate>
<asp:HiddenField ID="HiddenFieldDroitID" runat="server" Value='<%# Eval("droit_id") %>' />
<asp:CheckBox ID="CheckBoxDroit" runat="server" Text='<%# Eval("droit_label") %>' />
</ItemTemplate>
</asp:DataList>
I check them using code behind in the usercontrol :
Public Sub CheckRole(ByVal role As Integer)
For Each dliOrganisme As DataListItem In Me.DataListOrganismes.Items
Dim DataListDroits As DataList = dliOrganisme.FindControl("DataListDroits")
If DataListDroits IsNot Nothing Then
For Each dliDroit As DataListItem In DataListDroits.Items
If role = CInt(CType(dliDroit.FindControl("HiddenFieldDroitID"), HiddenField).Value) Then
Dim CheckBoxDroit As CheckBox = dliDroit.FindControl("CheckBoxDroit")
CheckBoxDroit.Checked = True
End If
Next ' DataListDroits
End If
Next ' DataListItem
End Sub
And in the page_load of the calling webform :
Dim CheckBoxesRoles1 As ASP.organisme_checkboxesroles_ascx = Me.FormViewRubrique.FindControl("CheckBoxesRoles1")
Dim rolesCoches As New List(Of Integer)
Dim cmdRoles As New SqlCommand("SELECT droit_id FROM o_droit_rubrique WHERE rubrique_id = #rubrique", conn)
cmdRoles.Parameters.AddWithValue("rubrique", Request.QueryString("rid"))
Dim rdrRoles As SqlDataReader = cmdRoles.ExecuteReader
While rdrRoles.Read
CheckBoxesRoles1.CheckRole(rdrRoles("droit_id"))
End While
rdrRoles.Close()
... and yet, they are not checked.
But if I do this :
Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
Dim CheckBoxesRoles1 As ASP.organisme_checkboxesroles_ascx = Me.FormViewRubrique.FindControl("CheckBoxesRoles1")
If CheckBoxesRoles1 IsNot Nothing Then
For Each role As Integer In CheckBoxesRoles1.CheckedRoles
Response.Write("role : " & role & "<br>")
Next
End If
End Sub
I tells me they are...
I'm going mad here ! Why does it tells me they are checked while they obviously are not ?
Well... for one thing, you aren't checking if your checkboxes are checked, all you're doing is outputting the value of "role". What exactly are you expecting here?
Two suggestions:
1) Set the Checked property of your CheckBox in the aspx like so:
<asp:CheckBox ID="CheckBoxDroit" runat="server" Text='<%# Eval("droit_label") %>' Checked='<%# (Eval("droit_id") > 0).ToString()' />
2) Set the property in OnItemDataBound in code-behind
One of two things is happening: Either the code you expect to be executing is not really executing (ie, is your if block ever true? Is the control not being found? Try a breakpoint), OR you are doing it at the wrong time -- after the page has already been rendered.

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