C# - How To Databind A Dropdownlist At Page Load
Jan 21, 2011
Assuming i have two dropdownlists namely: dropdownlistA and dropdownlistB. at page load, i bind values to dropdownlistA. however, depending on the value selected or displayed in dropdownlistA, i want to bind data to dropdownlistB.
Currently, i can bind data to dropdownlistA alright and i already have the required dataset and datatable bind data to dropdownlist. However, dropdownlistB does not bind at page load since the criteria for filling the dataset to bind dropdownlistB (which is the value of dropdownlistA) is not selected. how can i make this wwork.
I am currently considered if this might work. If i were to call the databind for dropdownlistA in a different declared method besides its binding in page load, and select the value from bind in the declared method, would any value be selected?
For example:
In during page load, i call the a method that returns dataset values which i bind to dropdownlistA(caseIDDropDownList). then i call another method (CreateexhibitDataSet()) which contains the dataset values for binding dropdownlistB(exhibitDropDownList). however, i need to define a criteria in the CreateExhibitDataset() method which i will use to generate the dataset values to bind dropdownlistB. if i were to call for the data bind of dropdownlistA(caseIDDropdownList) again in the CreateExhibitDataset() method and pick the value in the dropdown list, would i get any values?
How can i work around this to bind both dropdownlists on page load?
[Code]....
View 4 Replies
Similar Messages:
Jul 22, 2010
I posted a similar question previously, but none of the answers worked and I've been scouring all over the web trying to find a solution. My situation, I have a Edit Window webform with a dropdownlist (Note: to avoid confusion, I'm using Telerik extensions only to decorate the webform):
<%@ Page Language="VB" CodeFile="EditFormVB.aspx.vb" Inherits="EditFormVB" %>
<%@ Register Namespace="CustomBoundField" TagPrefix="custom" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Edit Pop-up</title>
</head>
<body class="">
<form id="form1" runat="server">
<div>
<script type="text/javascript">
function CloseAndRebind(args) {
GetRadWindow().BrowserWindow.refreshGrid(args);
GetRadWindow().close();
}
function GetRadWindow() {
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow; //Will work in Moz in all cases, including clasic dialog
else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow; //IE (and Moz as well)
return oWindow;
}
function CancelEdit() {
GetRadWindow().close();
}
</script>
<asp:ScriptManager ID="ScriptManager2" runat="server" />
<telerik:RadFormDecorator ID="RadFormDecorator1" runat="server" Skin="Vista" DecoratedControls="All" />
<br />
<br />
<asp:DetailsView ID="DetailsView1" DataKeyNames="ID" runat="server" AutoGenerateRows="False"
GridLines="None" DataSourceID="detailsSqlDataSource" Height="50px" Width="125px"
BorderWidth="0" CellPadding="0" CellSpacing="7">
<Fields>
<asp:BoundField DataField="TS_DESCRIPTION" HeaderText="TS_DESCRIPTION" SortExpression="TS_DESCRIPTION" />
<asp:BoundField DataField="TS_TITLE" HeaderText="TS_TITLE" SortExpression="TS_TITLE" />
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowInsertButton="True" />
</Fields>
</asp:DetailsView>--%>
<telerik:RadScriptManager ID="RadScriptManager1" runat="server" />
<telerik:RadFormDecorator ID="RadFormDecorator1" runat="server" Skin="Vista" />
<br />
<br />
<asp:DetailsView ID="DetailsView1" runat="server" Height="400px" Width="745px"
AutoGenerateRows="False" DataKeyNames="TS_ID" DataSourceID="SqlDataSource2"
EnableModelValidation="True">
<Fields>
<asp:TemplateField HeaderText="Category">
<EditItemTemplate>
<%--<asp:DropDownList ID="TTCategory" runat="server" DataSourceID="ReqCategoryData" SelectedValue='<%# Bind("TS_NAME") %>' />--%>
<asp:DropDownList DataSourceID="ReqCategoryData" DataTextField="ReqCategory" DataValueField="ReqCategory"
ID="reqCategoryDropDown" runat="server" AppendDataBoundItems="true" AutoPostBack="true" >
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Button" EditText="Update" ShowEditButton="True"
ShowCancelButton="True">
<ItemStyle HorizontalAlign="Center" />
</asp:CommandField>
</Fields>
</asp:DetailsView>
</div>
</form>
</body>
</html>
And in the code behind, I'm setting the datasource for the dropdownlist and using a function to query the DB for the name of the value I want to set as the selected value when the page loads initially: Partial Class EditFormVB Inherits System.Web.UI.Page
Public Shared category_Name As String = ""
Dim ddlDataSource As New SqlDataSource
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
DetailsView1.DefaultMode = DetailsViewMode.Edit
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.Page.Title = "Editing record"
''Setup DropDownList SqlDataSource
ddlDataSource.ID = "ReqCategoryData"
Page.Controls.Add(ddlDataSource)
ddlDataSource.ConnectionString = ConfigurationManager.ConnectionStrings("TTPRODReportsQuery").ConnectionString
ddlDataSource.SelectCommand = "SELECT TS_NAME AS ReqCategory FROM dbo.TS_SELECTIONS WHERE (TS_FLDID = 5299 AND TS_STATUS = 0) ORDER BY TS_NAME"
Dim args As New DataSourceSelectArguments
ddlDataSource.Select(args)
''Set max length of Title field to 70 characters
Dim dvrTest As DetailsViewRowCollection = DetailsView1.Rows
Dim TitleTB As TextBox = dvrTest.Item(0).Cells(1).Controls(0)
TitleTB.Attributes.Add("onkeydown", "isMaxLen(this)")
TitleTB.Attributes.Add("maxlength", "70")
Dim myDDL As DropDownList = DetailsView1.FindControl("reqCategoryDropDown")
''Perform dropdown list population operations
If Page.IsPostBack = False Then
Dim ticket_ID As String = getDataKey(DetailsView1)
''Fetch Category ID
Dim sqlText As String = "SELECT TS_REQCATEGORY FROM USR_ITFAC WHERE (TS_ID = " + ticket_ID + ") "
Dim reqDataReader As SqlDataReader = GetDataReader(sqlText)
reqDataReader.Read()
Dim category_ID As String = reqDataReader(0)
''Fetch Category name using the categoryID and set as selected value in dropdown list
sqlText = "SELECT TS_NAME FROM TS_SELECTIONS WHERE (TS_ID = " + category_ID + ") "
reqDataReader = GetDataReader(sqlText)
reqDataReader.Read()
category_Name = reqDataReader(0)
myDDL.DataBind()
myDDL.Selectedvalue = category_Name //<--this value gets set only when debugging,
End If
End Sub
Private Function GetDataReader(ByVal sqlText As String) As SqlDataReader
Dim dr As SqlDataReader
Dim sqlConn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("TTPRODReportsQuery").ConnectionString)
sqlConn.Open()
Dim sqlCmd As SqlCommand = New SqlCommand(sqlText, sqlConn)
dr = sqlCmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
Return dr
End Function
End Class
The dropdownlist does get populated appropriately, however when I attempt to set the value, it doesn't reflect when the page loads; the dropdownlist just gets populated and no value is set to selected in the markup, so the first value is shown by default. The odd thing is that when I'm debugging, the value appears to get set when I step through the function, it's as if the selectedvalue is getting reset as soon as the function exits and proceeds to load the page.
SOLUTION: Had to add a separate function that is called onLoad from the DropDownList after the after Page_Load is done executing. Still unresolved is why the the DropDownList rebinds after the Page_Load.
IN HTML:
<asp:DropDownList DataSourceID="ReqCategoryData" DataTextField="ReqCategory" DataValueField="ReqCategory"
ID="reqCategoryDropDown" runat="server" AutoPostBack="true" OnLoad="DDL_DataBound">
IN CODE-BEHIND
Public Shared category_Name As String = ""
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.Page.Title = "Editing record"
''Setup DropDownList SqlDataSource
ddlDataSource.ID = "ReqCategoryData"
Page.Controls.Add(ddlDataSource)
ddlDataSource.ConnectionString = ConfigurationManager.ConnectionStrings("TTPRODReportsQuery").ConnectionString
ddlDataSource.SelectCommand = "SELECT TS_NAME AS ReqCategory FROM dbo.TS_SELECTIONS WHERE (TS_FLDID = 5299 AND TS_STATUS = 0) ORDER BY TS_NAME"
Dim args As New DataSourceSelectArguments
ddlDataSource.Select(args)
''Set max length of Title field to 70 characters
Dim dvrTest As DetailsViewRowCollection = DetailsView1.Rows
Dim TitleTB As TextBox = dvrTest.Item(0).Cells(1).Controls(0)
TitleTB.Attributes.Add("onkeydown", "isMaxLen(this)")
TitleTB.Attributes.Add("maxlength", "70")
Dim myDDL As DropDownList = DetailsView1.FindControl("reqCategoryDropDown")
''Perform dropdown list population operations
If Page.IsPostBack = False Then
Dim ticket_ID As String = getDataKey(DetailsView1)
''Fetch Category ID
Dim sqlText As String = "SELECT TS_REQCATEGORY FROM USR_ITFAC WHERE (TS_ID = " + ticket_ID + ") "
Dim reqDataReader As SqlDataReader = GetDataReader(sqlText)
reqDataReader.Read()
Dim category_ID As String = reqDataReader(0)
''Fetch Category name using the categoryID and set as selected value in dropdown list
sqlText = "SELECT TS_NAME FROM TS_SELECTIONS WHERE (TS_ID = " + category_ID + ") "
reqDataReader = GetDataReader(sqlText)
reqDataReader.Read()
category_Name = reqDataReader(0)
myDDL.DataBind()
End If
End Sub
Protected Sub DDL_DataBound(ByVal sender As Object, ByVal e As System.EventArgs)
If Page.IsPostBack = False Then
Dim myDDL As DropDownList = DetailsView1.FindControl("reqCategoryDropDown")
myDDL.Items.FindByValue(category_Name).Selected = True
End If
End Sub
View 1 Replies
Oct 26, 2010
how to get the default value from a dropdownlist when the form load.
View 13 Replies
Sep 29, 2010
I can't get the following to set on page load. I want the month selected be the current month, on page load. What needs to change here?
[Code]....
View 6 Replies
Mar 12, 2011
vb Code:
SqlDataAdapter dd = new SqlDataAdapter("select * from book_store", conn);
DataSet ds;
ds=new DataSet();
dd.Fill(ds);
DropDownList1.DataSource=ds;
DropDownList1.DataValueField = "b_id";
DropDownList1.DataTextField = "b_qty";
I m not able to understand what is datavaluefiled and datatextfield are doing here ...... why i can't bind dropdownlist without these two property and what is is use ?Please provide me link if possible .. I m not able to find the correct keyword for searching
View 2 Replies
Apr 7, 2010
I have a DropDownList in my page, it DataBind with a objectDataSource.
when user select an option base that i have a FormView that show the detail of selected option an it also work with an othere ObjectDataSource.
when user insert, delete or edit an option for example the name of option will in edit mode changed and i need the DropDownList be refresh that show the new name of option.
i alredy know where should i write the code but i don't know how to refresh the DropDownList without dataBind the DropDownList because AppendDataBoundItems="True".
View 2 Replies
Feb 4, 2012
I have a drop down box , it has value that is retrieve from datasqlsource, however i want to get the count value on page load but it seem that it did not count
'Dim adapter As New SqlDataAdapter
'Dim ds As New DataSet
'Dim connectionString = ConfigurationManager.ConnectionStrings("myProject").ConnectionString
'Dim myConn As New SqlConnection(connectionString)
[Code] ....
View 1 Replies
Jan 12, 2011
This is my setup: I've got a dropdownlist of people and a linkbutton next to it to add a person. the linkbutton makes an update panel appear. When clicking save, I want the data to be saved and the new person be selected in the dropdown. As far as I can tell, I have done this properly. After I save the data I refresh the dropdownlist and take the new person's value and set it as the selected value. When stepping through, it shows the ddl with the new person and the new person selected! BUT, when the page comes back, the ddl is unchanged, ie NOT refreshed. I thought it might be something with the Update Panel but I got a similar setup to work on another page! It also works on a nested Update Panel (not shown in the following code). Can you think of why this "deception" is happening?
Here is some of my code.
[Code]....
View 5 Replies
Mar 17, 2011
I'm working on web pages that have an ASP DropDownList defined, and on page load the data source is bound to it through DataSource.DataBind(). When I step through the code, the drop down list does not show anything in it, but when the page actually displays, it does have items in the list. When exactly does DataBind() get applied to the control?
The problem is that some of the values returned by the SQL back end have a null Text, so nothing is displayed in the drop down list for that row. I want to just use the Value as the Text, but only if the Text is null. And when I put the code to loop through and do that right after the DataBind(), there is nothing in the drop down list at that point in the code.
View 3 Replies
Feb 15, 2010
I have a complex UserControl with the main purpose to encapsulate DropDownList with a number of properties for advanced manipulation.
List is being populated on PreRender event depending on properties previously were set:
protected void Page_PreRender(object sender, EventArgs e)
{
sourceClient.SelectCommand = this.Property1 ? "exec a" : "exec b";
}
The most used property is ClientID:
[Category("Settings")]
public int ClientID
{
get
{
return Int32.Parse(DropDownList1.SelectedItem.Value);
}
set
{
DropDownList1.Items.FindByValue(value).Selected = true;
}
}
Getter commonly is being called by ControlPameters in SqlDataSources on pages with this control.
Setter - from markup: <uc:UserControl1 runat="server" ClientID='<%# Bind("ID") %>' />.
Why does setter from Bind is called earlier then PreRender? And DropDownList is empty and item selecting doesn't work! How to workaround this behavior?
View 1 Replies
Dec 14, 2010
I want to create this scenario: The user selects a school from ddlSchool and this populates ddlStaff with a list of staffs in that school. i knw the codes for sql database but dont know how to do it for oracle.
View 5 Replies
Apr 13, 2010
Public Class PMRADGrid
Inherits System.Web.UI.GridView
Private Sub PMRADGrid_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
[code]...
View 1 Replies
Aug 13, 2010
I would rather not magic string my DataTextField/Values on the dropdownlist after setting up the source as a List collection of objects.
I was thinking I could use the DataSource properties but it doesn't seem to like the couple of ways I tried.
WORKS BUT NOT IDEAL
//set the datasource to the returned List<Cart>
this.cartDdl.DataSource = CartManager.Load(WebProfile.Current.UserName);
//set the DataValueField to the Cart.ID property
this.cartDdl.DataValueField = "ID";//would rather use the obj property Cart.ID
//set the DataTextField to the Cart.Description property
this.cartDdl.DataTextField = "Description";//would rather use the obj property Cart.Description
//Bind the ddl to the datasource
this.cartDdl.DataBind();
HOW I WOULD THINK IT COULD WORK this.cartDdl.DataValueField = ((Cart)this.cartDdl.DataSourceObject).ID; this.cartDdl.DataTextField = ((Cart)this.cartDdl.DataSourceObject).Description;
View 2 Replies
Oct 29, 2010
I created this generic method to Bind Controls on my ascx:
[Code]....
I cannot use a for cycle, it must be generic to load several DropDownList or CheckBoxLists on my web user control.
View 1 Replies
Apr 9, 2010
environment: VS2008 When running below code the DDLKlient.DataBind() appends the whole set of names to the already existing list. I.e. I have 2 sets of names in the DropDownList!Question:? what can I do to prevent appending and just get 1 (one) set of names?? is there any refresh option?
Protected Sub DVKlient_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertedEventArgs) Handles DVKlient.ItemInserted
Dim connString As String
[code]...
View 2 Replies
Aug 16, 2010
I was wondering, how about can i databind some custom attributes to my Radiobuttonlist / Dropdownlist / Checkboxlist? My existing code as follows:
With Me.ddlOtherApplications
.DataTextField = "ApplicationName" + Me.iSolutions_SysVariables.sys_iLanguage.Replace("-", "")
.DataValueField = "ApplicationID"
.DataSource = dtOtherApplications
.DataBind()
End With
However, I have 2 more additional custom attributes: ApplicationID and ApplicationImgUrl..... how abt do i databind these 2?
View 6 Replies
Mar 21, 2010
i'm opening a new window and passing on to it variables in a querystring, the values are loaded into a function that is filling my dataset and then filling my Gridview. after i press the button field in my grid to delete an item, the databind doesn't show the updated grid but remains the same. i've noticed that if i navigate back and refresh i see it correctly. in FF btw no problem.
the code:
this is used to open the new window
[Code]....
[Code]....
[Code]....
[Code]....
View 3 Replies
Aug 10, 2010
i have one dropdownlist in the gridview. i have to load that dropdownlist when that page is loaded. dropdownlist should contain the country list from country table
View 7 Replies
Feb 25, 2010
I hv Declared two Master page one Is Base and Derived.. Base Page Load is working but when i hv written load controls in Derived Page Load Using C# it's not working..
View 3 Replies
Oct 7, 2010
I'm trying to resolve correct paths to javascript scripts in my head section using:
<script src="<%# ResolveUrl("~/Scripts/jquery-1.4.2.min.js") %>" type="text/javascript" />
In order to resolve the path I need to call databind using Page.Header.DataBind(); What event should I place the databind call in?
[URL]
When I put it in Page_Load as the article it works (only for firefox), but I wonder if this is the correct place.
When I follow this article IE 8 renders:
<script src="/Scripts/jquery-1.4.2.min.js" type="text/javascript" />
and firefox 3.6 correctly renders:
<script src="../../Scripts/jquery-1.4.2.min.js" type="text/javascript" />
Update:
Fixed browser issues by updating a script reference in a referenced user control to use ResolveUrl. Now browser issues are fixed. Still wondering where to put Databind.
View 2 Replies
Jan 19, 2010
How need I to refresh my page after SqlDataSource1.DataBind(); for my GridView appears this new data.
View 1 Replies
May 21, 2010
i got this inside a button inside a datalist
CommandName="<%# Container.ItemIndex %>"
when i click the button, i'm expecting commandname to = 0, then 1, then 2, etc, as the datalist progresses, and i'm using that value in the button click's c#but i'm getting this error, i'm pretty sure i'm using this exact setup on another page and i have no problems, any idea what's going on?Server Error in '/' Application.
Compilation ErrorDescription: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.Compiler Error Message: CS0117: 'System.Web.UI.Control' does not contain a definition for 'ItemIndex'
View 1 Replies
Jul 7, 2010
I am trying to create a progress bar for page load as it takes long to load. I need help to resolve jscript error 'null' is null or not an object on line $get("btn").click();
[Code]....
View 3 Replies
May 14, 2010
Control ctrl = new Control();
this.PlaceHolder1.Controls.Clear();
ctrl = Page.LoadControl("uc1.ascx");
ctrl.ID = "DynamicCtrl";
this.PlaceHolder1.Controls.Add(ctrl);
instead of using a control to load can we load a page .. like example.aspx
page mypage=new page();
mypage= Page.Load("example.aspx");
how to do this. as i am getting the erro
View 5 Replies
Apr 11, 2010
I have a update panel on the ASPX page,When thepage loads the content in the update panel shouldnot load ( Update panel should show the Updatepanel progress control) but after page load update panel contents should load . How do i get this efect.
View 3 Replies