Showing posts with label based. Show all posts
Showing posts with label based. Show all posts

Thursday, March 29, 2012

Poplulating Text Field with DropDown selection

Hi folks. Here's a simple question. Trying to populate some text fields based on a dropdown menu selection, but it doesn't work. When a selection is made in the dropdown menu, it seems to default to the selectedValue =2. Not sure why. Any advice would be much appreciated. Thanks! Here's the code:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { TextBox1.Text =""; TextBox2.Text =""; TextBox3.Text ="";if (DropDownList1.SelectedValue =="0") TextBox1.Text ="blah";if (DropDownList1.SelectedValue =="1") TextBox1.Text ="blahblah";if (DropDownList1.SelectedValue =="2") TextBox1.Text ="blahblahblah"; }

Are you dynamicalluy populating the dropdown list in your code behind? If you are, the Page_OnLoad event is running which is populating your dropdownlist on every postback. To make sure this doesnt happen, you should populate when teh page is not posted back. in other words...

if(!Page.IsPostback){// populate my dropdownlist}

If you are not dynamically populating the dropdownlist, please make sure your viewstate is turned on, that way the server knows that index to preserve when the page is loaded again.

EnableViewState="true"

Hope this helps.


If you are adding the items to the dropdown through code in Page_Load then check if they are inside If (!Ispostback) block.


hi..

i think u can have a break point in the page load or start of selected index changed event..

and find the value..

if not..

check in the design view that item 2 isSelected=true..

correct me if i'm wrong..


Thanks to all for the suggestions. The dropDownList was statically populated from the control properties in the ASPX page. I tinkered with this for a long while, but could NOT get it to work. So, I changed approach and populated the list by making an array in the code, and now it works as designed. Thanks again. Here is the code, in case anybody is interested.

protected void Page_Load(object sender, EventArgs e) {if (!IsPostBack) {// 2 dimensional array for dropDown liststring[,] forms = { {"blah","0"}, {"blah blah","1"}, {"blah blah blah","2"} };// populate listfor (int i = 0; i < forms.GetLength(0); i++) {//add both text and value DropDownList1.Items.Add(new ListItem(forms[i, 0], forms[i, 1])); } } }protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) {if (DropDownList1.SelectedIndex != -1) { TextBox1.Text = DropDownList1.SelectedItem.Text; } }

FYI... regarding the orginal post, the reason the textBox wasn't populated correctly was a simple syntax error. Used cascading IF statement without ELSE IF or switch statement.

Populate 2nd dropdown list based on selecteditem in first with out postback?

Hi All:

I have an aspx page that has 2 dropdownlists. I want to populate the second
dropdownlist based on the selecteditem in the first dropdown. I know I can
do this by doing a post back and using the selectedindex and loading the
second dropdownlist.

Is there anyway I can do this without doing a postback? Any ideas/pointers
will be much appreciated.

Thanks!

VinayYou'll have to use JavaScript in the client.

search: dependent listbox

<%= Clinton Gallagher
METROmilwaukee (sm) "A Regional Information Service"
NET csgallagher AT metromilwaukee.com
URL http://metromilwaukee.com/
URL http://clintongallagher.metromilwaukee.com/

"Vinay" <vinay_hs_removethis@.nospam.yahoo.com> wrote in message
news:ef$cOw4oFHA.2976@.TK2MSFTNGP12.phx.gbl...
> Hi All:
> I have an aspx page that has 2 dropdownlists. I want to populate the
> second dropdownlist based on the selecteditem in the first dropdown. I
> know I can do this by doing a post back and using the selectedindex and
> loading the second dropdownlist.
> Is there anyway I can do this without doing a postback? Any ideas/pointers
> will be much appreciated.
> Thanks!
> Vinay
Thanks for the pointer - will do some reading and see if I can implement it.

"clintonG" <csgallagher@.REMOVETHISTEXTmetromilwaukee.com> wrote in message
news:ek$zp%234oFHA.3656@.TK2MSFTNGP09.phx.gbl...
> You'll have to use JavaScript in the client.
> search: dependent listbox
> <%= Clinton Gallagher
> METROmilwaukee (sm) "A Regional Information Service"
> NET csgallagher AT metromilwaukee.com
> URL http://metromilwaukee.com/
> URL http://clintongallagher.metromilwaukee.com/
>
> "Vinay" <vinay_hs_removethis@.nospam.yahoo.com> wrote in message
> news:ef$cOw4oFHA.2976@.TK2MSFTNGP12.phx.gbl...
>> Hi All:
>>
>> I have an aspx page that has 2 dropdownlists. I want to populate the
>> second dropdownlist based on the selecteditem in the first dropdown. I
>> know I can do this by doing a post back and using the selectedindex and
>> loading the second dropdownlist.
>>
>> Is there anyway I can do this without doing a postback? Any
>> ideas/pointers will be much appreciated.
>>
>> Thanks!
>>
>> Vinay
>>

Populate 2nd dropdown list based on selecteditem in first with out postback?

Hi All:
I have an aspx page that has 2 dropdownlists. I want to populate the second
dropdownlist based on the selecteditem in the first dropdown. I know I can
do this by doing a post back and using the selectedindex and loading the
second dropdownlist.
Is there anyway I can do this without doing a postback? Any ideas/pointers
will be much appreciated.
Thanks!
VinayYou'll have to use JavaScript in the client.
search: dependent listbox
<%= Clinton Gallagher
METROmilwaukee (sm) "A Regional Information Service"
NET csgallagher AT metromilwaukee.com
URL http://metromilwaukee.com/
URL http://clintongallagher.metromilwaukee.com/
"Vinay" <vinay_hs_removethis@.nospam.yahoo.com> wrote in message
news:ef$cOw4oFHA.2976@.TK2MSFTNGP12.phx.gbl...
> Hi All:
> I have an aspx page that has 2 dropdownlists. I want to populate the
> second dropdownlist based on the selecteditem in the first dropdown. I
> know I can do this by doing a post back and using the selectedindex and
> loading the second dropdownlist.
> Is there anyway I can do this without doing a postback? Any ideas/pointers
> will be much appreciated.
> Thanks!
> Vinay
>
Thanks for the pointer - will do some reading and see if I can implement it.
"clintonG" < csgallagher@.REMOVETHISTEXTmetromilwaukee
.com> wrote in message
news:ek$zp%234oFHA.3656@.TK2MSFTNGP09.phx.gbl...
> You'll have to use JavaScript in the client.
> search: dependent listbox
> <%= Clinton Gallagher
> METROmilwaukee (sm) "A Regional Information Service"
> NET csgallagher AT metromilwaukee.com
> URL http://metromilwaukee.com/
> URL http://clintongallagher.metromilwaukee.com/
>
> "Vinay" <vinay_hs_removethis@.nospam.yahoo.com> wrote in message
> news:ef$cOw4oFHA.2976@.TK2MSFTNGP12.phx.gbl...
>

Monday, March 26, 2012

populate a dg column based upon the value populated to another row in the datagrid

Is it possible when populating a datagrid to populate a dropdownlist
column based upon the value populated to another row in the datagrid?
(i.e. I have a drop down which I want to populate differently for each
row with user names based upon a UserRegionID which is also a column in
the row).
Since you don't actually know the value of the UserRegionID until the
data is already bound to the datagrid, how do you do this?
Thanks,
Mike
*** Sent via Developersdex http://www.examnotes.net ***You can use the datagrid events (RowDataBound I think) to handle this
by populating your dropdown using the id of each row as the grid is
populated
HTH
---
David Gray
ASP.NET/C# Developer/Architect (MCAD.NET)
On Fri, 13 Jan 2006 02:23:16 -0800, Mike P <mike.parr@.gmail.com>
wrote:

>Is it possible when populating a datagrid to populate a dropdownlist
>column based upon the value populated to another row in the datagrid?
>(i.e. I have a drop down which I want to populate differently for each
>row with user names based upon a UserRegionID which is also a column in
>the row).
>Since you don't actually know the value of the UserRegionID until the
>data is already bound to the datagrid, how do you do this?
>
>Thanks,
>Mike
>
>*** Sent via Developersdex http://www.examnotes.net ***

populate a dg column based upon the value populated to another row in the datagrid

Is it possible when populating a datagrid to populate a dropdownlist
column based upon the value populated to another row in the datagrid?
(i.e. I have a drop down which I want to populate differently for each
row with user names based upon a UserRegionID which is also a column in
the row).

Since you don't actually know the value of the UserRegionID until the
data is already bound to the datagrid, how do you do this?

Thanks,

Mike

*** Sent via Developersdex http://www.developersdex.com ***You can use the datagrid events (RowDataBound I think) to handle this
by populating your dropdown using the id of each row as the grid is
populated

HTH

-------------
David Gray
ASP.NET/C# Developer/Architect (MCAD.NET)

On Fri, 13 Jan 2006 02:23:16 -0800, Mike P <mike.parr@.gmail.com>
wrote:

>Is it possible when populating a datagrid to populate a dropdownlist
>column based upon the value populated to another row in the datagrid?
>(i.e. I have a drop down which I want to populate differently for each
>row with user names based upon a UserRegionID which is also a column in
>the row).
>Since you don't actually know the value of the UserRegionID until the
>data is already bound to the datagrid, how do you do this?
>
>Thanks,
>Mike
>
>*** Sent via Developersdex http://www.developersdex.com ***

Populate a ListBox based on database search

I am trying to populate a ListBox with values retrieved from a database based on a search. I have a TextBox in which the user will enter the text they wish to search for, a Button which will submit the text, and then a ListBox which is invisible until values are returned from the database. I have a SqlDataSource with a SelectCommand saying "SELECT * FROM [table] WHERE [name] LIKE '@dotnet.itags.org.Parameter'". I want to know how to bind the value in the TextBox to the "@dotnet.itags.org.Parameter" in the Sql statement. I am quite new at programming, and I'm sure this is quite a simple task. Any help would be appreciated.

MYSQL:

myCommand.Parameters.Clear();
myCommand.CommandText = "SELECT * FROM [table] WHERE [name] LIKE (?)";
myCommand.Parameters.Add(new OdbcParameter(null, txtSearch.Text));

MSSQL:

myCommand.Parameters.Clear();
myCommand.CommandText = "SELECT * FROM [table] WHERE [name] LIKE @.search";
myCommand.Parameters.Add(new SqlParameter("@.search", txtSearch.Text));


Thanks for the reply. Where would I put this code? I'm using MSSql, but I am not using any stored procedures. All my SQL code is on my .aspx page. Should this go somewhere on my .aspx page or in my VB codebehind?

This would go in your code behind, in the onclick method from your button (double click your submit button and you'll go automatically to your onclick method).

Remember the code I gave in the example is C# code, I don't know the correct syntax in VB.net but it should get you started.


This should help:

http://www.asp.net/learn/dataaccess/default.aspx?tabid=63

Cheers

populate calendar

Hello Everyone,

I'm very new to asp.net. I want to populate calendar based on given date, e.g. if date is 7/11/05, I want to populate calendar from 11 to 31 and showing month on the top. Can please someone give me an idea how should I start it? Is there any built in function for it? I don't need code for it. I would appreciate if someone could tell me how should I start working on it?
Thank you

Hi,
start fromCalendar.SelectedDates

Saturday, March 24, 2012

populate one dropdownlist based on the selected of another dropdownlist

hi
i am using c# asp.net
i have one datagrid in my form and i bound two dropdown list using coding. i loaded my database values in my first dropdown list by using this code:

private void Page_Load(object sender, System.EventArgs e)
{// Put user code to initialize the page here
if(!Page.IsPostBack)
{ BindData();
PopulateList();
}
}
public void BindData()
{
SqlDataAdapter ad = new SqlDataAdapter("SELECT Course_NAME FROM JTSISControlManager_Course",conn);
DataSet ds = new DataSet();
ad.Fill(ds,"JTSISControlManager_Course");
DataGrid2.DataSource = ds;
DataGrid2.DataBind();

}
public DataSet PopulateList()
{

SqlDataAdapter ad = new
SqlDataAdapter("SELECT Course_Name FROM JTSISControlManager_Course", conn);

DataSet ds = new DataSet();
ad.Fill(ds,"JTSISControlManager_Course");
return ds;
}

here is the html coding:

<form id="Form1" method="post" runat="server">
<asp:datagrid id="DataGrid2" style="Z-INDEX: 101; LEFT: 328px; POSITION: absolute; TOP: 64px"
runat="server" Width="408px" AutoGenerateColumns="False" DataKeyField="Course_NAME">
<Columns>
<asp:BoundColumn DataField="Course_NAME" HeaderText="Course_NAME" />
<asp:TemplateColumn>
<HeaderTemplate>
<aspropDownList ID="Dropdownlist1" Runat="server" DataTextField="Course_NAME" OnSelectedIndexChanged ="DropDown_SelectedIndexChanged" DataSource =" <%#PopulateList()%> " AutoPostBack="True" />
<aspropDownList ID="Dropdownlist3" Runat="server" DataTextField="Dept_NAME" AutoPostBack="True" />
</HeaderTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid></form>

then using the following code i retreived my first dropdownlist value

protected void DropDown_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList list = (DropDownList)sender;
li=list.SelectedValue.Trim();
Response.Write(li);

}

my need is i want to use the retreived value of the first dropdownlist in query and fill the values in my second dropdownlist of the datagrid.
tell me how to use that retreived value of first dropdown list in next qurey and how to fill the second dropdownlist .so please help me to do this. give example coding to do my requirement
Edit/Delete MessageHi karthikeyan,

In my application I've Make and Model dropdowns. Model dropdown gets populated as soon as we select a make in a dropdown, it gets all the models for that make;

Here is my code;

Populating Model Dropdown
private void ddlMake_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (ddlMake.SelectedValue != "")
{
PopulateFieldsInDropDowns("SELECT cat.DisplayText Model, to_char(cat.CATEGORYID) ModelID FROM TDCATEGORIES cat WHERE cat.CATEGORYLEVEL=4 and parentid= " + ddlMake.SelectedValue + " ORDER BY cat.DisplayText", ddlModel);
}
else
ddlModel.Items.Clear();
}

Populate Method
private void PopulateFieldsInDropDowns(string sqlQuery, DropDownList drpList)
{
try {
conn.Open();
OleDbCommand cmCommand = new OleDbCommand(sqlQuery, conn);
OleDbDataReader dreader = cmCommand.ExecuteReader();

drpList.Items.Clear();
drpList.Items.Add(new ListItem("", ""));

while (dreader.Read())
{
drpList.Items.Add(new ListItem(dreader.GetString(0), dreader.GetString(1)));
}

dreader.Close();

if (dreader != null)
dreader = null;

if (cmCommand != null)
cmCommand.Dispose();
}
catch
{
drpList.Items.Clear();
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Cannot Get Data: Cannot Get Required Data.";
}
conn.Close();
}

It should rock.

thanks,
hi ahmarshi,

i tried which u given, but i got error:
System.NullReferenceException: Object reference not set to an instance of an object.

my first dropdown name is DropDownList1 and second name is ddlmodel
i modified my coding like this:
protected void DropDown_SelectedIndexChanged(object sender, System.EventArgs e)
{
DropDownList list = (DropDownList)sender;
li=list.SelectedValue.Trim();
Response.Write(li);

if (li != "")
{
PopulateFieldsInDropDowns("SELECT Dept_NAME from JTSISControlManager_Department where Course_ID in (select Course_ID from JTSISControlManager_Course where Course_NAME= '" + li + "')", ddlmodel);
}
else
ddlmodel.Items.Clear();
}
private void PopulateFieldsInDropDowns(string sqlQuery, DropDownList drpList)
{
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
SqlDataReader dreader =cmd.ExecuteReader();


drpList.Items.Clear();
drpList.Items.Add(new ListItem("", ""));

while (dreader.Read())
{
drpList.Items.Add(new ListItem(dreader.GetString(0), dreader.GetString(1)));
}

dreader.Close();

if (dreader != null)
dreader = null;

if (cmd!= null)
cmd.Dispose();
}
catch
{
drpList.Items.Clear();
//lblMessage.ForeColor = System.Drawing.Color.Red;
Response.Write ( "Cannot Get Data: Cannot Get Required Data.");
}
conn.Close();
}

i kept break point and run this but while comming to
this line
private void PopulateFieldsInDropDowns(string sqlQuery, System.Web.UI.WebControls.DropDownList drpList)
in the drplist comes <undefined value>.
then after comming to this line
drpList.Items.Add(new ListItem("", ""));
it automatically goes to catch.please tell me and give sugestion to rectify this prooblem.

Wednesday, March 21, 2012

Populating a DataGrid with a Stored Procedure based on ddl values

Hello All -

First off, I am a complete newbie.

I have created a page with 5 dropdownlists that I populated using stored procedures.

Question one:

How Do I display a default value for these Dropdowns?

I have configured a DataGrid using another Stored Procedure.

Question 2:

How Do I populate the DG with the values specified within the 5 dropdownlists using a stored procedure?

Here is a copy of the current aspx page.

<%@dotnet.itags.org.PageLanguage="VB"MasterPageFile="~/MasterPage.master"Title="CTM PreRunbook" %>

<asp:ContentID="Content1"ContentPlaceHolderID="ContentPlaceHolder1"Runat="Server">

<table><tr><thalign="center"colspan="3"style="vertical-align: middle; text-align: center"valign="middle">

<asp:LabelID="Label1"runat="server"Font-Size="Large"Text="Data Feed Query"></asp:Label> </th></tr>

<tr>

<th>

Application Name:</th>

<tdalign="right"style="vertical-align: top; text-align: left">

<tdstyle="width: 31px">

<asp:DropDownListID="ddlAppName"runat="server"AutoPostBack="True"DataSourceID="SqlDataSource1"DataTextField="AppName"DataValueField="AppName">

<asp:ListItem>- Select -</asp:ListItem>

</asp:DropDownList><asp:SqlDataSourceID="SqlDataSource1"runat="server"ConnectionString="<%$ ConnectionStrings:PreRunbookConnectionString %>"

SelectCommand="spGet_AppName"SelectCommandType="StoredProcedure"></asp:SqlDataSource>

</td></tr>

<tr>

<th>

Data Feed Name:</th>

<tdalign="right"style="vertical-align: top; text-align: left">

<tdstyle="width: 31px; text-align: left;">

<asp:DropDownListID="ddlDataFeedName"runat="server"AutoPostBack="True"DataSourceID="SqlDataSourceDependantFeeds"DataTextField="FeedName"DataValueField="FeedName">

</asp:DropDownList><asp:SqlDataSourceID="SqlDataSourceDependantFeeds"runat="server"

ConnectionString="<%$ ConnectionStrings:PreRunbookConnectionString %>"SelectCommand="spGet_FeedNames"

SelectCommandType="StoredProcedure"></asp:SqlDataSource>

</td></tr>

<tr>

<th>

Account:</th>

<tdalign="right"style="vertical-align: top; text-align: left">

<tdstyle="width: 31px">

<asp:DropDownListID="ddlAccount"runat="server"AutoPostBack="True"DataSourceID="SqlDataSourceServiceAccount"DataTextField="ServiceAccounts"DataValueField="ServiceAccounts">

</asp:DropDownList><asp:SqlDataSourceID="SqlDataSourceServiceAccount"runat="server"

ConnectionString="<%$ ConnectionStrings:PreRunbookConnectionString %>"SelectCommand="spGetDistinctServiceAccounts"

SelectCommandType="StoredProcedure"></asp:SqlDataSource>

</td></tr>

<tr>

<th>

Platform:</th>

<tdalign="right"style="vertical-align: top; text-align: left">

<tdstyle="width: 31px; text-align: left;">

<asp:DropDownListID="ddlPlatform"runat="server"AutoPostBack="True"DataSourceID="SqlDataSourcePlatform"DataTextField="Platform"DataValueField="Platform">

</asp:DropDownList><asp:SqlDataSourceID="SqlDataSourcePlatform"runat="server"ConnectionString="<%$ ConnectionStrings:PreRunbookConnectionString %>"

SelectCommand="spGet_Platform"SelectCommandType="StoredProcedure"></asp:SqlDataSource>

</td></tr>

<tr>

<th>

Scheduled Run Days:</th>

<tdalign="right"style="vertical-align: top; text-align: left">

<tdstyle="width: 31px">

<asp:DropDownListID="ddlSchedRunDays"runat="server"AutoPostBack="True"DataSourceID="SqlDataSourceSchedRunDays"DataTextField="ScheduledRunDays"DataValueField="ScheduledRunDays">

</asp:DropDownList><asp:SqlDataSourceID="SqlDataSourceSchedRunDays"runat="server"

ConnectionString="<%$ ConnectionStrings:PreRunbookConnectionString %>"SelectCommand="spGet_ScheduledRunDays"

SelectCommandType="StoredProcedure"></asp:SqlDataSource>

</td></tr>

</Table>

<table>

<tr>

<tdstyle="width: 100px"align="center">

<asp:ButtonID="btnFilter"runat="server"Text="Filter"/></td>

<tdstyle="width: 100px">

<asp:ButtonID="btnReset"runat="server"Text="Reset"/></td>

</tr>

<tr>

<tdcolspan="2"align="center">

<asp:ButtonID="btnShowAllDataFeeds"runat="server"Text="Show All Data Feeds"/></td>

</tr>

</table>

<br/>

<asp:GridViewID="GridView1"runat="server"AllowPaging="True"AllowSorting="True"

AutoGenerateColumns="False"DataSourceID="SqlDataSourceGridView">

</asp:GridView>

<asp:SqlDataSourceID="SqlDataSourceGridView"runat="server"ConnectionString="<%$ ConnectionStrings:PreRunbookConnectionString %>"

SelectCommand="spFilterByServAcct"SelectCommandType="StoredProcedure">

<SelectParameters>

<asp:FormParameterFormField="ServiceAccounts"Name="ServAcct"

Type="String"/>

</SelectParameters>

</asp:SqlDataSource>

<br>

</asp:Content>

Thanks ,

Pat

here is the best example that describes your needs

http://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/data/sqldatasource.aspx

populating a drop down list based on the date

Hi, I'm looking to populate a drop down list with the month and year for the next 12 months from the current date, codeing in C#

any help would be great, thanks

this will show the next 12 months in a textbox, not to hard for you to convert to a drop down list

 DateTime date =new DateTime(2007, 02, 11);for (int i = 1; i <= 12; i++) { txtOutput.Text += date.AddMonths(i).ToShortDateString() +"\r"; }

check out this code below... its working for me...

protected void Button2_Click(object sender, EventArgs e) {for (int iCount = 0; iCount < 12; iCount++) { DropDownList1.Items.Add(DateTime.Now.AddMonths(iCount + 1).ToString("MMMM"));if (DropDownList2.Items.FindByText(DateTime.Now.AddMonths(iCount + 1).ToString("yyyy")) ==null) DropDownList2.Items.Add(DateTime.Now.AddMonths(iCount + 1).ToString("yyyy")); } }

hope it helps./.

Friday, March 16, 2012

Populating a listbox from DB w/o postback

Hi,

I have 2 listboxes. The first gets populated from the db as soon as the page loads. The second listbox get populated based on the user's selection from the first listbox. However, currently the code is such that with each selection there is a postback. We want to avoid it using filter and javascript. I am not using ADO.NET but adodbc and no datagrids or datasets (please don't tell me that i should as my boss clearly doesn't want to get into it at this stage).

How can i do it?

Thanks

Currently the code with the postback is as follows:
page_load

if not page.ispostback then
Do While Not rs.EOF
li = New ListItem(rs("cat_name").Value, rs("cat_id").Value)
List1.Items.Add(li)
rs.MoveNext()
Loop

End If

'List1.SelectedIndex = 0
rs.Close()
rs = Nothing

List1.SelectedValue = cat_id

'here there is some other code not relevant to the listboxes

'select items for second listbox
Dim rsSub As New ADODB.Recordset
rsSub.Open("SELECT sub_name, sub_id FROM subs WHERE cat_id=" & cat_id.ToString & " ORDER BY sub_name ASC", cn)
Dim l_item As ListItem
Do While Not rsSub.EOF
l_item = New ListItem(rsSub("sub_name").Value, rsSub("sub_id").Value)
List2.Items.Add(l_item)
rsSub.MoveNext()
Loop

List2.SelectedValue = sub_id

rsSub.Close()
rsSub = Nothing

cn.Close()
End If
' End If

End If

End Sub

Protected Sub Select1Change(ByVal sender As System.Object, ByVal e As System.EventArgs)

Dim cn As New ADODB.Connection
cn.Open(YBayTools.Constants.ConnectionString)

Dim rs As New ADODB.Recordset
Dim li As ListItem

rs.Open("Select * from subs where cat_ID =" & List1.SelectedItem.Value.ToString, cn)
'rs.Open("Select * from subs where cat_ID ='" & List1.SelectedItem.Text.ToString & "' & List1.SelectedItem.value.ToString", cn)

Dim strCat As String

If List2.Items.Count > 0 Then
List2.Items.Clear()
End If

If rs.BOF And rs.EOF Then
Response.Write("no records found")
Else

Do While Not rs.EOF
li = New ListItem(rs("sub_name").Value, rs("sub_id").Value)
List2.Items.Add(li)
rs.MoveNext()

Loop

End If

rs.Close()
rs = Nothing
cn.Close()You code is done to work with postback. So write client-site code with javascript on the first listBox and in this code, read the DB and populate you other listBox.
That's the thing I am not sure how to write it in jscript.
I need to get the data for both listboxes from a db.
You can use an XmlHttp object from client-side script, but this will probably only work on IE and Mozilla. Other solutions could use a lot of script and hidden frames (beuark!)

Populating a textbox with a datasource

I have a textbox that needs to get it's value from database based on a value parsed from text in another textbox.

I am using a datasource with a select command to hit the database, but I have no need to collect anything but a single value, so it seems very wasteful to have to load anything into a dataset or the like, just to get that one thing to a textbox.

What's the easiest way to get this one value for the textbox?

thanks

Did you thought keep the data in a Session variable?

Your select command should similar to below

SELECT ID FROM table WHERE ID='1'

Now you could use one SqlCommand.ExecuteScalar which only returns 1 value from the database.

Check below link for more information

http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx

HC


rsegecin:

Did you thought keep the data in a Session variable?

That wouldn't do much because I wouldstill have to do all the fetching to get itinto the session variable, or any other variable for that matter.


Haissam:

Your select command should similar to below

SELECT ID FROM table WHERE ID='1'

Now you could use one SqlCommand.ExecuteScalar which only returns 1 value from the database.

Check below link for more information

http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx

HC

Yes that is very similar to the SQL I'm using

I was considering ExecuteScalar thought, the drawback is really that it's still a lot of code for one little value, and I have been reusing the datasources pretty religiously so far, eliminating the need for much code at all.

I'm hoping to keep that up, but maybe there is no particularly simple way... I wish datasources had a Scalar command that returned the value :/

Populating Controls - Form Load Dynamically

hi all,
how can I populate one aspx form when page is loading based on page ID? for
example:
loading page A (to search for VB code) would display labels and texboxes,
dropdown lists all related to VB, plus the address bar would show something
like this: www.somethinghere?id=3
and if you change number 3 from the address bar to (for example) 34 or 71
you would get different page with the same formatting like I.e:
www.somethinghere?id=34 would load the page related to C# topics and all
labels and texboxes and dropdown lists related to C# OR
www.somethinghere?id=71 would load the page related to ASP.NET for example
and labels and textboxes would be populated according to ASP.NET and so
on...

my question is, how do they do that? they must assign an ID number for each
topic but then how they populate all controls on that ONE page accordingly?

I am very much interested in this approach and wants to know how its done
and how can I get more info about it. I think its better than duplicating
pages if you were going to use them over and over?

what do you think?

please let me know

thanksid=XX part of the url is available as Request.QueryString.
Request.QueryString["id"] for www.somethinghere?id=71 will return "71".
PageLoad event code can read the id and setup the page controls accordingly.

--
Eliyahu Goldin,
Software Developer & Consultant
Microsoft MVP [ASP.NET]

"netasp" <netasp@.newsgroups.nospamwrote in message
news:O6fQ523xGHA.3488@.TK2MSFTNGP02.phx.gbl...

Quote:

Originally Posted by

hi all,
how can I populate one aspx form when page is loading based on page ID?
for example:
loading page A (to search for VB code) would display labels and texboxes,
dropdown lists all related to VB, plus the address bar would show
something like this: www.somethinghere?id=3
>
and if you change number 3 from the address bar to (for example) 34 or 71
you would get different page with the same formatting like I.e:
www.somethinghere?id=34 would load the page related to C# topics and all
labels and texboxes and dropdown lists related to C# OR
www.somethinghere?id=71 would load the page related to ASP.NET for example
and labels and textboxes would be populated according to ASP.NET and so
on...
>
my question is, how do they do that? they must assign an ID number for
each topic but then how they populate all controls on that ONE page
accordingly?
>
I am very much interested in this approach and wants to know how its done
and how can I get more info about it. I think its better than duplicating
pages if you were going to use them over and over?
>
what do you think?
>
please let me know
>
thanks
>
>


thanks Eliyahu for your reply,

does this method considered to be a good or bad practice with visual studio
2005? because I also have seen some other web applications using different
pages for each category page, their address bar would show aspx pages I.e
employee.aspx, manager.aspx, supervisor.aspx instead of loading everything
into one template page.

I just want to know what is the best practice and recommendation for such a
scenario?

thanks again

"Eliyahu Goldin" <REMOVEALLCAPITALSeEgGoldDinN@.mMvVpPsS.orgwrote in
message news:%23mXBFJ5xGHA.4732@.TK2MSFTNGP03.phx.gbl...

Quote:

Originally Posted by

id=XX part of the url is available as Request.QueryString.
Request.QueryString["id"] for www.somethinghere?id=71 will return "71".
PageLoad event code can read the id and setup the page controls
accordingly.
>
--
Eliyahu Goldin,
Software Developer & Consultant
Microsoft MVP [ASP.NET]
>
"netasp" <netasp@.newsgroups.nospamwrote in message
news:O6fQ523xGHA.3488@.TK2MSFTNGP02.phx.gbl...

Quote:

Originally Posted by

>hi all,
>how can I populate one aspx form when page is loading based on page ID?
>for example:
>loading page A (to search for VB code) would display labels and texboxes,
>dropdown lists all related to VB, plus the address bar would show
>something like this: www.somethinghere?id=3
>>
>and if you change number 3 from the address bar to (for example) 34 or 71
>you would get different page with the same formatting like I.e:
>www.somethinghere?id=34 would load the page related to C# topics and all
>labels and texboxes and dropdown lists related to C# OR
>www.somethinghere?id=71 would load the page related to ASP.NET for
>example and labels and textboxes would be populated according to ASP.NET
>and so on...
>>
>my question is, how do they do that? they must assign an ID number for
>each topic but then how they populate all controls on that ONE page
>accordingly?
>>
>I am very much interested in this approach and wants to know how its done
>and how can I get more info about it. I think its better than duplicating
>pages if you were going to use them over and over?
>>
>what do you think?
>>
>please let me know
>>
>thanks
>>
>>


>
>


Hello Netasp,

In ASP.NET, dynamically creating webcontrols is naturally supported. Here
are some web articles introducing this:

#HOW TO: Dynamically Create Controls in ASP.NET by Using Visual C# .NET
http://support.microsoft.com/kb/317794/EN-US/
#Adding Controls to a Web Forms Page Programmatically
http://authors.aspalliance.com/aspx...dingcontrolstow
ebformspageprogrammatically.aspx

#How to: Add Controls to an ASP.NET Web Page Programmatically
http://msdn2.microsoft.com/en-us/library/kyt0fzt1.aspx
for your scenario, you want to generate two page UI for different client
user requests(search for VB or c#), I think you need to consider the
following things:

Which one is more important for our application, flexibiilty or
performance?

When we dynamically create the page UI depend on different client requests,
it make the page very flexible and easy to extend when you want to add
additional UI template(such as search for J#...). However, the drawback
here is that dynamically creating control will add performance overhead
which is less efficient than statically compiled and loaded page/controls.
Also, making the page UI dynamically generated will make the line of code
in your page increase significantly.

IMO, for those pages which as definitely different code logic and business
purpose or the UI differ from each other obviously, I would recommend you
create separate page for each one.

If the UI of those pages are similar and easy to be templated, you can
consider creating a page to dynamically generate UI.

Please feel free to let me know if you have any further questions.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead

This posting is provided "AS IS" with no warranties, and confers no rights.
thank you Steven for your reply,

how about this:
I create the page and add all the necessary controls to it, dropdown list,
an image box, labels and some textboxes (with generic names) -// so there is
not an overhead of creating controls dynamically

then, if the user clicks the ASP.NET link for example (and lets say it has
been assigned ID=1) then I go to my database and load the appropriate
control names and images for the C# page! OR if the user clicks C# link
(which lets also assume it has been assigned to ID=21) then I will load from
another table all the appropriate names for labels, textboxes and images for
that C# page.

what do you think? would that cut half of my overhead expenses? considering
the controls are already been created?

I would love to hear your input on this approach.

thank you very much for the links

"Steven Cheng[MSFT]" <stcheng@.online.microsoft.comwrote in message
news:hp8bsa$xGHA.4220@.TK2MSFTNGXA01.phx.gbl...

Quote:

Originally Posted by

Hello Netasp,
>
In ASP.NET, dynamically creating webcontrols is naturally supported. Here
are some web articles introducing this:
>
#HOW TO: Dynamically Create Controls in ASP.NET by Using Visual C# .NET
http://support.microsoft.com/kb/317794/EN-US/
>
#Adding Controls to a Web Forms Page Programmatically
http://authors.aspalliance.com/aspx...dingcontrolstow
ebformspageprogrammatically.aspx
>
#How to: Add Controls to an ASP.NET Web Page Programmatically
http://msdn2.microsoft.com/en-us/library/kyt0fzt1.aspx
>
for your scenario, you want to generate two page UI for different client
user requests(search for VB or c#), I think you need to consider the
following things:
>
Which one is more important for our application, flexibiilty or
performance?
>
When we dynamically create the page UI depend on different client
requests,
it make the page very flexible and easy to extend when you want to add
additional UI template(such as search for J#...). However, the drawback
here is that dynamically creating control will add performance overhead
which is less efficient than statically compiled and loaded page/controls.
Also, making the page UI dynamically generated will make the line of code
in your page increase significantly.
>
IMO, for those pages which as definitely different code logic and business
purpose or the UI differ from each other obviously, I would recommend you
create separate page for each one.
>
If the UI of those pages are similar and easy to be templated, you can
consider creating a page to dynamically generate UI.
>
Please feel free to let me know if you have any further questions.
>
>
Sincerely,
>
Steven Cheng
>
Microsoft MSDN Online Support Lead
>
>
>
This posting is provided "AS IS" with no warranties, and confers no
rights.
>


Thanks for your reply Netasp,

As for the new idea you mentioned, do you mean you predefine all the
controls on the page and assigned fixed ID for each one. and dynamically
load their string resources( such as Text ...) from file or database and
assign to their "Text" property? If this is the case, I think it doable.

Of course, if the controls are defined at design-time, it will save lots of
dynamic control creating and loading overhead.

Please let me know if you have any further questions.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead

This posting is provided "AS IS" with no warranties, and confers no rights.
thanks Steven for your reply,

yeah, this is very much the idea, and I think its better than creating more
than one aspx page that does exactly the same thing.

it seems doable so far, and I will pick up any issues as I advance.

thanks for your help.

best regard,

"Steven Cheng[MSFT]" <stcheng@.online.microsoft.comwrote in message
news:9Q8DZ2nyGHA.4616@.TK2MSFTNGXA01.phx.gbl...

Quote:

Originally Posted by

Thanks for your reply Netasp,
>
As for the new idea you mentioned, do you mean you predefine all the
controls on the page and assigned fixed ID for each one. and dynamically
load their string resources( such as Text ...) from file or database and
assign to their "Text" property? If this is the case, I think it doable.
>
Of course, if the controls are defined at design-time, it will save lots
of
dynamic control creating and loading overhead.
>
Please let me know if you have any further questions.
>
Sincerely,
>
Steven Cheng
>
Microsoft MSDN Online Support Lead
>
>
This posting is provided "AS IS" with no warranties, and confers no
rights.
>
>


Thanks for the followup Netasp,

Yes, this is a good idea. Actually, what you do is just how ASP.NET
application do localization support for web pages. ASP.NET support creating
resource files for each page or the whole application and we can load
string or other resource(like image, files) from resource file according
different CultureInfo. So for your case here, instead of depending on
CultureInfo, your page's resource are depend on other criteria.

Please feel free to post here if you meet any further problem.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead

This posting is provided "AS IS" with no warranties, and confers no rights.
now I have one final question,
what is the best reliable way of loading a control value from a database?
lets say I have label1 already sitting in my webform how can I load its
content "Books" from a table1 in sql 2005 database?

do I use a normal adapter to loop through? is there a good examples
illustrating how to accomplish that?

thanks
"netasp" <netasp@.newsgroups.nospamwrote in message
news:%235MSXCtyGHA.284@.TK2MSFTNGP02.phx.gbl...

Quote:

Originally Posted by

thanks Steven for your reply,
>
yeah, this is very much the idea, and I think its better than creating
more than one aspx page that does exactly the same thing.
>
it seems doable so far, and I will pick up any issues as I advance.
>
thanks for your help.
>
best regard,
>
"Steven Cheng[MSFT]" <stcheng@.online.microsoft.comwrote in message
news:9Q8DZ2nyGHA.4616@.TK2MSFTNGXA01.phx.gbl...

Quote:

Originally Posted by

>Thanks for your reply Netasp,
>>
>As for the new idea you mentioned, do you mean you predefine all the
>controls on the page and assigned fixed ID for each one. and dynamically
>load their string resources( such as Text ...) from file or database
>and
>assign to their "Text" property? If this is the case, I think it
>doable.
>>
>Of course, if the controls are defined at design-time, it will save lots
>of
>dynamic control creating and loading overhead.
>>
>Please let me know if you have any further questions.
>>
>Sincerely,
>>
>Steven Cheng
>>
>Microsoft MSDN Online Support Lead
>>
>>
>This posting is provided "AS IS" with no warranties, and confers no
>rights.
>>
>>


>
>


Hi Netasp,

how you'll read the static data from database depend on how will you use
them. If you will only load them at each page's startup time and will
requrey database if require them later, I suggest you use Sqlcommand +
DataReader to query the data since this will have better performance.

If you will load the data and also cached them in local memory for later
use, you can consider use TableAdpater and return them in the form of
DataTable, Dataset ...

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead

This posting is provided "AS IS" with no warranties, and confers no rights.

Populating Drop down box value

Hello,

i want to populate the drop down box values based on the first drop down box
value, actually i have form in which user will select a car maker and based
on that value below 2 drop down box values will be populated
For example user select Suzuki and based on that value in one drop down car
models will be shown and in secound one car type will be shown, how can i do
it in ASP.NET, please tell me, i'm using MS-Access DB.
Thanks.in the onselectedindexchanged event of the first control you need to
bind the second dropdown to a datasource passing the selected item
value from the first dropdown (control.selecteditem.value)

for instance:

if model id is an integer:

string selectCommand = "select model_id, model from table where
model_id =" + ddlMake.selecteditem.value;

if model id is an string:

string selectCommand = "select model_id, model from table where
model_id ='" + ddlMake.selecteditem.value + "'";

Populating Drop down box value

Hello,
i want to populate the drop down box values based on the first drop down box
value, actually i have form in which user will select a car maker and based
on that value below 2 drop down box values will be populated
For example user select Suzuki and based on that value in one drop down car
models will be shown and in secound one car type will be shown, how can i do
it in ASP.NET, please tell me, i'm using MS-Access DB.
Thanks.in the onselectedindexchanged event of the first control you need to
bind the second dropdown to a datasource passing the selected item
value from the first dropdown (control.selecteditem.value)
for instance:
if model id is an integer:
string selectCommand = "select model_id, model from table where
model_id =" + ddlMake.selecteditem.value;
if model id is an string:
string selectCommand = "select model_id, model from table where
model_id ='" + ddlMake.selecteditem.value + "'";

Populating Drop Down Lists Based on Another DDL

Sounds like your repopulating the first dropdown in the load event. Try
wrapping the code that populates the first drop down in a
"IsPostBack==False" type check.

"Ben Arthur" <skchbs@dotnet.itags.org.yahoo.com> wrote in message
news:uHDS6CHAEHA.4080@dotnet.itags.org.TK2MSFTNGP09.phx.gbl...
> OK...assume the first ddl has 2 values"USA" & Australia", when i select
> USA, it populates the states correctly in the second ddl, but then if i
> select australia also, as it is autopostback, it comes back to USA as
> selected n so i cannot get the second DDL to populate to values for
> Australia...the datagrid however does bind correctly according to the
> states selected...
> Please let me know if I shoudl explain better....
> Thanks for ur time
> Ben
>
> *** Sent via Developersdex http://www.developersdex.com ***
> Don't just participate in USENET...get rewarded for it!Yes ! Thanks, that worked...but i m not sure of how to handle
postbacks....i.e i load the first ddl only the first time, it loads the
USA and australia, then i select one of them, it loads second ddl
accordingly and builds the datagrid,but if i select australia, it
populates the second ddl but does not bind the grid.....though the
binding is not related to postback but to the selectedindexhanged(i shud
mention there is only value for the second ddl in my DB for first
ddl=australia)...is it related to the postback ...or is it because there
is only one value?
Thanks again for ur help.
Ben

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
My usual process for this is...

Put your grid-data-binding in a method/function/sub of its own. Call this
from the page load (wrapped in a isPostBack==False) then in each of your
drop down list events you can call the grid databind method.

BTW, do you really need a grid, they are very "heavy".

"Ben Arthur" <skchbs@.yahoo.com> wrote in message
news:u5jF9ZHAEHA.2800@.tk2msftngp13.phx.gbl...
> Yes ! Thanks, that worked...but i m not sure of how to handle
> postbacks....i.e i load the first ddl only the first time, it loads the
> USA and australia, then i select one of them, it loads second ddl
> accordingly and builds the datagrid,but if i select australia, it
> populates the second ddl but does not bind the grid.....though the
> binding is not related to postback but to the selectedindexhanged(i shud
> mention there is only value for the second ddl in my DB for first
> ddl=australia)...is it related to the postback ...or is it because there
> is only one value?
> Thanks again for ur help.
> Ben
> *** Sent via Developersdex http://www.developersdex.com ***
> Don't just participate in USENET...get rewarded for it!
thanks a lot...i had to put the binding code in postback part too n now
it works fine...

Thanks again
Ben

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Populating Dropdown List

Hi all,

I am not able to select any value from my dropdownlist,it always returns the first value. Based on the selection the corresponding record should be displayed in a text box. I have given my code here. I am totally frustrated. Pls check it out.

Page_load event
If Not Page.IsPostBack Then
sql = "select scode from supplier"
cmd = New SqlCommand(sql, con)
read = cmd.ExecuteReader
While (read.Read)
ddlscode.Items.Add(read.Item(0))
End While
ddlscode.DataBind()
End If

Private Sub ddlscode_SelectedIndexChanged(...)...
Dim sql As String
Dim i As Integer
Dim tempscode As String
con.Open()
sql = "select * from supplier "
cmd = New SqlCommand(sql, con)
adap = New SqlDataAdapter(cmd)
dt = New DataTable()
adap.Fill(dt)
For i = 0 To dt.Rows.Count - 1
If dt.Rows(i).Item("scode") = ddlscode.SelectedItem.Value Then
txtsaddr.Text = dt.Rows(i).Item("saddr")
End If
Next
read.Read()
read.Close()
con.Close()
End Subtry setting the View state of the control to true.

Set AutoPostback property equal to true.and write this code in page load

if(!page.IsPostback)

{

SqlDataReader rr;

rr=Com.ExecuteReader();

DropDownList1.DataSource=rr;

DropDownList1.DataBind();

}

Select the Value Selected value of DropdownList as

DropDownList1.SelectedItem.Text

I hope this will work but this is in c# convert into Vb


Not sure what's causing you problem, but it might be linked to your loop in the second function. A better way of handling it might be:

Private Sub ddlscode_SelectedIndexChanged(...)...
Dim sql As String
con.Open()
sql = "select saddr from supplier where scode = '" & ddlscode.SelectedItem.Value & "'"
Dim sqlComm As new System.Data.SqlClient.SqlCommand(sql,con);
txtsaddr.Text = sqlComm.ExecuteScalar()
con.Close()
End Sub

The SQL should only return 1 row (I've assumed the selected code is a text value) and the ExecuteScalar call returns the first column (in this case the 'saddr')

Hope this helps,
Nic