Showing posts with label form. Show all posts
Showing posts with label form. Show all posts

Thursday, March 29, 2012

Pop up windows

Hi,

How to make pop up window from code behine without using
java script. And another thing is that, how to pass value
from the pop up window to a form if there is a textbox in
the pop up. ThanksMaking popup windows is a client task and as such it can be done only with
client tools. The only way to create a popup is javascript showModalDialog
call.

You can pass a value back from popup in window.returnValue property. The
javascript showModalDialog statement that started the popup will get this
value as a result of the call.

Eliyahu

"Souljaz" <Souljaz@.discussions.microsoft.com> wrote in message
news:1ddd01c52de9$9e89fb80$a401280a@.phx.gbl...
> Hi,
> How to make pop up window from code behine without using
> java script. And another thing is that, how to pass value
> from the pop up window to a form if there is a textbox in
> the pop up. Thanks

Pop up windows

Hi,
How to make pop up window from code behine without using
java script. And another thing is that, how to pass value
from the pop up window to a form if there is a textbox in
the pop up. ThanksMaking popup windows is a client task and as such it can be done only with
client tools. The only way to create a popup is javascript showModalDialog
call.
You can pass a value back from popup in window.returnValue property. The
javascript showModalDialog statement that started the popup will get this
value as a result of the call.
Eliyahu
"Souljaz" <Souljaz@.discussions.microsoft.com> wrote in message
news:1ddd01c52de9$9e89fb80$a401280a@.phx.gbl...
> Hi,
> How to make pop up window from code behine without using
> java script. And another thing is that, how to pass value
> from the pop up window to a form if there is a textbox in
> the pop up. Thanks

pop up windows

Hi!

I have programmed in Java and Windows form but very new to ASP and web in general. It is very primitive question but currently, I do not know. I want a small pop up windows with close or the like button that will appear when I click on a button. In Java or NET, you can use show method but in ASP or Webmatrix in particular, what component should I use .

Regards.Hello, check my BLOG, I have an article on how to pop up a window from inside ASP.NET

regards
I'm sure haidar's blog shows the proper method - but to help clear up for future knowledge..
Popping up a web page is a client-side event. The .Net server can't feed a popup to your browser- think of all the uncontrollable popups that would occur if the server-side could do this. opening a popup is a clients-ide event using javascript (window.open method)
Hope that helps - and it's a common question - understanding what events are client-side and what are server-side will help avoid confusion
Of course the contents of the popup can be totally designed (perhaps as a web user control) on the server side from within .NET and then merely instanciated in the javascipt. This gives full access to all of the .NET design environment features for the pop-up.

ps: I have not read the blog entry, so that *may* how it is done there also...
Hi!

I use Javascript but as very primitive programmer, I just am able to have this code:

<a onclick="window.open('materialchecking.aspx textbox=txtStartDate','cal','width=250,height=225,left=270,top=180')" href="http://links.10026.com/?link=javascript:;">
<input type="button" value="Check" /></a
It works fine as static page. However, what if I want to transfer some variable value from main page to the pop up windows to do the checking or other way around, do ing some data processing when button is clicked and transfer the result in to the pop up. I guess, there should be other approach as the href is perhaps too simple to do that.

Regards.
Hello, please check my BLOG below, I have an article on how to pop up windows inside asp.net

regards
Sorry!

I did not go to Pop up before and just went to your personal website and could not see the article (!1).

OK. But now question is that I want to transfer some data between master page and pop up windows. How is it possible. Suppose pop up windows is to show the number of stock in record and in store is not different. So when button is clicked, I have top go to server-side database to do something and finally transfer thw TWO number to the pop up. So how to do that.

Thank you so much for your attention.
ok, you might use the Querystring to pass values to the child window

regards
Hi!

I would really appreaciate if you can show me a bit of code to pass A VALUE to child windows.

Regards.
using function in blog...


*************************************
Javascript pop up window script
*************************************
<SCRIPT TYPE="text/javascript">
<!--
function popupform(myform, url, windowname)
{
// don't allow if we don't have the focus
if (! window.focus)return true;

// open the new window,
window.open(url, windowname, 'width=250,height=225,left=270,top=180,scrollbars=yes');
myform.target=windowname;
return true;
}
//-->
</SCRIPT>

then in your link...


<a onclick="popupform(this,'materialchecking.aspx?id='+ document.getElementById('textbox1').value,'cal')" href="http://links.10026.com/?link=javascript:"><input type="button" value="Check" /></a>
</body>
<input type="button" value="Check" /></a>

one of many ways probably .......

HTH
Hi!

Please forgive me if I apprea to be a bit dump. I am quite new to the field. As far as I understand, the call: document.getElementById is to set the value of textbox 1 to cal var. So in the pop up page, which command I should use to EXTRACT that value for use.
In MSDN page, i says that we can pass a colection of value. That is fine, Juts search var by id inb Collection. But I mean what command to EXTRACT those value in the page after we pass that value in the open up command.

To help make it clear, suppose I have an page asking for the invoice number. As within an invoice, there can be many materials with different quantity and price so I decide that after use enter the Supplier and Invoice number, user will be presented with Pop up windows that has text box and dropdownlist to enter list of data. But in this Pop up windows , the Supplier name and invoice name shold be present. I am looking for way to show the Suplier name and Invoice number on the Pop up windows.

Thank you very much for your attention.
in the example - the id of the invoice is being passed using "querystring"
if you look up at the address of this forum page- you will see "?tabindex=1&PostID=782635&mode=flat"
or something like that - this is called the querystring. It is passed as part of the url the client is requesting. In this example there are 3 things being passed - tabindex,postid, and mode
On the page being called- you can access theses values by using

dim myPostID as string
dim myTabIndex as string
dim myMode as string

myPostID = request.querystring("tabindex")
myTabIndex = request.querystring("PostID")
myMode = request.querystring("mode")

then i can use this any way i need to such as..
Sub Page_Load()
dim mySQL as string="Select * from posts WHERE PostId=" & MyPostID
....................

not exact code - but you get the idea

if on the first page, you already hace the supplier and invoice number - then you can pass that in the querystring as such

a onclick="popupform(this,'materialchecking.aspx?Supplier='+ document.getElementById('textbox1').value+ "&Invoice=" + document.getElementById('textbox2').value,'mypopupwindow_name')"

on the recieving page materialchecking.aspx - you would use

Sub Page_Load()
dim MySupplier as string = request.querystrin("Supplier")
dim MyInvoice as string = request.querystrin("Invoice")

HTH
Thank you uncleb1

They all work now. Apart from "&Invoice=" I have to change to '&Invoice' (!!!!cheer), all work and I learn a lot from this doing. Thank you
Hi again!

Now there is more challenge. Suppose I have an textbox that must be filled. I use RequiredValidator. Problem is that with "normal" button, I can write the code for validator but I do not know how for the ´button, created with javascript. Basically, the Pop up windows only works if textbox is not empty.
if you used this function


<SCRIPT TYPE="text/javascript">
<!--
function popupform(myform, url, windowname)
{
// don't allow if we don't have the focus

if (! window.focus)return true;
// open the new window,
window.open(url, windowname, 'width=250,height=225,left=270,top=180,scrollbars=yes');
myform.target=windowname;
return true;
}
//-->
</script>
......... you have a place to check for null

<SCRIPT TYPE="text/javascript">
<!--
function popupform(myform, url, windowname)
{

// don't allow if textbox is blank
if documet.getElementById(textbox1).value="" return true;

// don't allow if we don't have the focus
if (! window.focus)return true;
// open the new window,
window.open(url, windowname, 'width=250,height=225,left=270,top=180,scrollbars=yes');
myform.target=windowname;
return true;
}
//-->
</script>

or you could use a serverside asp textbox and use the built in asp validation - check out this tutorial
http://www.dotnetjunkies.com/QuickStart/aspplus/default.aspx?url=/quickstart/aspplus/doc/webvalidation.aspx

HTH

Pop Ups

Hi

I am using a popup, I launch the popup from a form, the user then choses an item on the popup, which is put into a session variable and then another form is launched. This works OK except the original form which launched the popup is still open how do I close it when the popup is launch. I use the code below to launch the popup

Dim sTempAsString

sTemp = "<script>window.open('LPopUpContractor.aspx',null,'top=150,left=250,height=150,width=450,status=yes,scrollbars=yes,toolbar=yes,menubar=yes,location=no');</script>"

Response.Write(sTemp)

Response.Flush()

Thanks

Louisa

Hi,
you can close the form from its container window,
<!-- Put this script in MyMainForm.aspx -->
<script type="text/javascript">
window.open('myPopupForm.aspx');
window.close();
</script>

or let the popup close the window that launched it,
<!-- Put this script in myPopupForm.aspx -->
<script type="text/javascript">
if(window.opener) {
window.opener.close();
}
</script>

This works brillantly, but I now get a popup before mine saying:

The Web page you are viewing is trying to close the window

Do you want to close this window?

I click on the yes and my popup appears, how do I get rid of the error msg popup?

Thanks

Louisa


Hi,
it is not an error message popup, it is an Internet Explorer security setting that prevents a script to close a window that wasn't opened by the script itself, without the user permission... well, it seems that a workaround exists for Internet Explorer, just try to set the window.opener property to some value. For example
<script type="text/javascript">
window.opener = this;
window.open('myPopup.aspx');
window.close();
</script>

but I'm not sure it will work on all browsers.


Hi,

The above doesn't seem to work for me as it just puts the pages into a loop, can I not close a previous page from the page load of the new page, when the new page is fully loaded?

Thanks

Louisa


Hi,
I don't know if a workaround exists for the security popup. Try to post this question in theClient Side Web Develoment section of these forums.

a little discussion about that same pop-up

http://forums.asp.net/962609/ShowPost.aspx


Hi,
thanks for posting the link, onewisehobbit.

Monday, March 26, 2012

Populate a DropDownList

I need to populate a dropdownlist with items form one SQL Table in SqlDataSource1 but the selected value and the data text need to match the ones that are already into another SQL Table in SqlDataSource2.

Any Sugestions?

You can manually compare the data between the tables in codebehind using the classes found in System.Data.SqlClient & System.Data.Sql. Then you can use the DropDownList.Items.Add(new ListItem()) methods to add new items to your dropdownlist.

Saturday, March 24, 2012

Populate DropDown with dataview

I have a bunch of dropdown on my form and I am trying to optimize the populating process. I am filling a dataview with a store proc and pass the dataview to each dropdown's datasource with a filter and sort expression. Until then every thing is fine however I need to add a black row at the top of each drop down and I dont know how to add it to my dataview or directly to dropdown. Any help would be great.

Here is what I got up to now


fctFillDropDownList(ddSource, 30, strSortAsc, dvTemp)
...

'*************************************************************************
'*************************************************************************
Private Sub fctFillDropDownList(ByRef objControl As System.Web.UI.WebControls.DropDownList, _
ByVal iParentID As Int16, ByVal strSort As String, ByRef dvTemp As DataView)
'*************************************************************************
dvTemp.RowFilter = "parentId=" & iParentID
dvTemp.Sort = strSort
objControl.DataSource = dvTemp
objControl.DataTextField = "Texte"
objControl.DataValueField = "Texte"
End Sub

After you call DataBind on the dropdownlist, you can do this (C# syntax):

MyDropDownList.Items.Insert(0, new ListItem("", ""));

That will add a blank row at the beginning of the dropdownlist.

HTH
Thanks that worked

populate FormView fields from a DropDownList

Hi,
I'm trying to build an online form using asp.net and vb.net for the
code behind in Visual Studio 2005.
I want to fill 3 fields in a FormView that's connected to one table
(table1) with information from another table (table2) by choosing the
key field from table2 in a DropDownList.
Table2 has 3 fields with info that doesn't change (name, phone# and
email for about 5 customer service reps). I want each rep to choose
their name in the DropDownList to populate those fields in the
FormView.
I'm connecting to the sql db with an ObjectDataSource.
I'm thinking I just need to put some VB code into the
SelectedIndexChanged event of the ddl, something like:
*something goes here* = DropDownList1.SelectedValue.ToString()
But I'm drawing a blank on what would go to the left of the equal
sign.
Thanks in advance for the help.myFormView.FindControl("myControlId") will find the control if it is in the
template the formview is going to present. Otherwise you may need to do
something like myFormView.EditItemTemplate.FindControl("myControlId").
Eliyahu Goldin,
Software Developer
Microsoft MVP [ASP.NET]
http://msmvps.com/blogs/egoldin
http://usableasp.net
"mkidd" <michaelk@.volkcorp.com> wrote in message
news:19842b1a-bab5-4594-aaef-c1cf99efd809@.u10g2000prn.googlegroups.com...
> Hi,
> I'm trying to build an online form using asp.net and vb.net for the
> code behind in Visual Studio 2005.
> I want to fill 3 fields in a FormView that's connected to one table
> (table1) with information from another table (table2) by choosing the
> key field from table2 in a DropDownList.
> Table2 has 3 fields with info that doesn't change (name, phone# and
> email for about 5 customer service reps). I want each rep to choose
> their name in the DropDownList to populate those fields in the
> FormView.
> I'm connecting to the sql db with an ObjectDataSource.
> I'm thinking I just need to put some VB code into the
> SelectedIndexChanged event of the ddl, something like:
> *something goes here* = DropDownList1.SelectedValue.ToString()
> But I'm drawing a blank on what would go to the left of the equal
> sign.
> Thanks in advance for the help.
Thanks, but can you help me with what to do to write the data from the
DropDownList table to the FormView after the FindControl event? I'm
really new at this.
On Jan 14, 9:15 am, "Eliyahu Goldin"
<REMOVEALLCAPITALSeEgGoldD...@.mMvVpPsS.org> wrote:
> myFormView.FindControl("myControlId") will find the control if it is in th
e
> template the formview is going to present. Otherwise you may need to do
> something like myFormView.EditItemTemplate.FindControl("myControlId").
> --
> Eliyahu Goldin,
> Software Developer
> Microsoft MVP [ASP.NET]http://msmvps.com/blogs/egoldinhttp://usableasp.net
> "mkidd" <micha...@.volkcorp.com> wrote in message
> news:19842b1a-bab5-4594-aaef-c1cf99efd809@.u10g2000prn.googlegroups.com...
>
>
>
>
>
>
>
>
>

Populate form fields

How do you populate individual form fields from a database? I have used datasets in the past but this time I need to do individual form fields.

Below is the code I tried and I know that reader only read 1 parameter and not the way I have it setup now to do multiple parameters.

thanks

1Dim sConnStrAs String = ConfigurationManager.ConnectionStrings("accmon").ConnectionString23'************************45Dim MySqlAs String ="SELECT * FROM privacyscan WHERE privacyscanDelete = 0 and url ='" & privacyAddress & "'"67 Dim reader As OleDb.OleDbDataReader89 Dim MyConn As New OleDbConnection(sConnStr)10 Dim Cmd As New OleDbCommand(MySql, MyConn)1112 MyConn.Open()13 reader = Cmd.ExecuteReader()1415 While reader.Read()16 txtOA.Text = reader("oa")17'txtDate.Text = reader("date")18 'txtURL.Text = reader("url")19 'txtReport.Text = reader("report")20 'txtScan11.Text = reader("chkpt_scan_11")21 'txtPass11.Text = reader("chkpt_pass_11")22 'txtScan14.Text = reader("chkpt_scan_14")23 'txtPass14.Text = reader("chkpt_pass_14")24 'txtScan15.Text = reader("chkpt_scan_15")25 'txtPass15.Text = reader("chkpt_pass_15")26 'txtScan22.Text = reader("chkpt_scan_22")27 'txtPass22.Text = reader("chkpt_pass_22")28 'txtScan31.Text = reader("chkpt_scan_31")29 'txtPass31.Text = reader("chkpt_pass_31")30 'txtScan32.Text = reader("chkpt_scan_32")31 'txtPass32.Text = reader("chkpt_pass_32")32 'txtScan41.Text = reader("chkpt_scan_41")33 'txtPass41.Text = reader("chkpt_pass_41")34 'txtScan41a.Text = reader("chkpt_scan_41a")35 'txtPass41a.Text = reader("chkpt_pass_41a")36 'txtScan41b.Text = reader("chkpt_scan_41b")37 'txtPass41b.Text = reader("chkpt_pass_41b")38 'txtScan42.Text = reader("chkpt_scan_42")39 'txtPass42.Text = reader("chkpt_pass_42")40 'txtScan43.Text = reader("chkpt_scan_43")41 'txtPass43.Text = reader("chkpt_pass_43")42 'txtScan44.Text = reader("chkpt_scan_44")43 'txtPass44.Text = reader("chkpt_pass_44")44 'txtScan71.Text = reader("chkpt_scan_71")45 'txtPass71.Text = reader("chkpt_pass_71")46End While47 reader.Close()48 MyConn.Close()

Well, if you uncomment the lines below then your code should be working fine. However, if your query returns more than one row, your controls will only show the last row returned (since you have a while loop).

Another thing you might want to check is the layout of your table. It doesn't seem very normalized ;-)


What is the problem with the current code? However everytime you need to make sure you are returning only one row.

Populate insert form field from GridView selection

Hi,

I'm trying to do something that seems like it should be simple, but I'm having trouble getting it to work. I have a page with a GridView and a FormView in Insert mode.

When the user selects a row in the gridview, I want to take the data keys from that selection and populate them to the appropriate textboxes in the form. I'm trying to do this in the

"GridView1_SelectedIndexChanged event" with the following code:

TextBox t;

t = (TextBox)FormView1.FindControl("myTextBox");

t.Text = (String)GridView1.SelectedDataKey.Values[0];

The text in "myTextBox" doesn't change, it remains blank. I've tried to find another event in which to put this code but so far no luck. I'm a newbie so I'm sure it's something obvious.

Can anyone help me with this? Thanks in advance.

Try moving your code to the FormView.DataBound event.


Hi Ed,

When I do that, I get "Object reference not set to an instance of an object. " I'm guessing that this is because the formview1_databound fires when the page is first loading, before there is a selected key from the gridview. I'm not sure that this is the case, it's just my best guess.

Do you have any suggestion for a workaround or alternate approach?

Thanks.


Once try this

ProtectedSub GridView1_SelectedIndexChanged(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles GridView1.SelectedIndexChanged

Formview1.PageIndex = GridView1.SelectedIndex

EndSub


Hi Mahesh,

Okay, now I have this code but I still don't see the text I want populated into the text box. What am I doing wrong?

protectedvoid GridView1_SelectedIndexChanged(object sender,EventArgs e)

{

FormView1.PageIndex = GridView1.SelectedIndex;

TextBox t;

t = (TextBox)FormView1.FindControl("myTextBox");

t.Text = (String)GridView1.SelectedDataKey.Values[0];

}


How about this:


protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{

for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (GridView1.SelectedIndex == i)
{
TextBox t;

t = (TextBox)FormView1.FindControl("myTextBox");
t.Text = (String)GridView1.SelectedDataKey.Values[0];
}
}
}


Within your FormView.DataBound event, simply place a conditional statement which checks for the existence of a SelectedItem.

if (!GridView1.SelectedIndex.Equals(-1))


That did it! Thanks very much (I told you that I was a newbie :-).

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

populate value in dropdown

Hi, I have an update form which contains the selected employee information. I was able to use DataReader to retrieve the data from the database. I want to place the department value in the dropdown which contains other department values so user can change the dept value and save the information. How can I display my department value in the dropdown? I was able to populate the dropdown without any problem except the department value wasn't highlighted. It is like a person originally worked at Marketing department and is going to switch to IT.

Thanks in advance.

<asp:DropDownListID="DDDept"runat="server"AutoPostBack="True" DataSourceID="ObjectDataSource1"DataTextField="DeptName"DataValueField="DeptID"Style="z-index: 112; left: 372px;position: absolute; top: 415px"Width="159px"></asp:DropDownList>

SO you have your datasource all set up and the drop down list displays the departments correctly. However you want the users current department to be selected..

use the SelectedValue Property of the drop down list and set it to whatever key field in the users table that has the department id in it.

<asp:DropDownList SelectedValue='<# Bind("DepartmentIdFieldFromUsersTable") %>' .../>

should do it.

hth,

mcm


Hi, Thank you so much for the help!! I can see the department correctly now !!

populating & Submitting an external form

Hey All,

In windows forms this can be done using the microsoft web browser control, but how is it done in asp.net either using the axwebbrowser control or httpwebrequest methods

this is an example description only actul sites and stuff will be different

I want my web site to do a search on google so on my site the user enters the input value into a text box, and they press send data.
This is then passed to google via some kind of magic, (ie webrequest) and we populate the google input box and press the search button, when we get our results back from google, i run the response via my regular expression and display the results in my own format.

I dont actully want to spider googles results its just the method is the closest description i can give to what i want to do.

I have been looking at posting data with the httpwebrequest and response methods but im not sure on it.

Can someone advise of the best possible method to handle such events

regards

Carlbump
Try the Google Web Services, even the free subscription allows you loads of searches.
You just make your own pages but use Google to do the searches, very straightforward.
i did say that i only was using google as an example

Populating a Dataset

I've created a vb windows application and written the following function within a class (class1). I dragged a dataset onto my form and renamed it datBookInfo but when I run the code I don't get anything in the form.

Please tell me what I'm doing wrong.


Public Overloads Function GetBookInfo() As DataSet
Dim oPubConnection As SqlConnection
Dim SConnString As String
Dim osqlCommPubs As SqlCommand
Dim osqlCommTitles As SqlCommand
Dim oDataAdapterPubs As SqlDataAdapter
Dim oDataAdapterTitles As SqlDataAdapter

Try
SConnString = "Data Source=(local);Initial Catalog=Pubs;" & _
"User ID=sa;Password=;"
oPubConnection = New SqlConnection(SConnString)
oPubConnection.Open()

'Create command to retrieve pub info
osqlCommPubs = New SqlCommand
osqlCommPubs.Connection = oPubConnection
osqlCommPubs.CommandText = "Select Pub_ID, Pub_Name from Publishers"

'Create Data Adapter for pub info
oDataAdapterPubs = New SqlDataAdapter
oDataAdapterPubs.SelectCommand = osqlCommPubs

'Create command to retrieve title info
osqlCommTitles = New SqlCommand
osqlCommTitles.Connection = oPubConnection
osqlCommPubs.CommandText = "select Pub_ID, title, price, ytd_sales from titles"

'Create data adapter for title info
oDataAdapterTitles = New SqlDataAdapter
oDataAdapterTitles.SelectCommand = osqlCommTitles

'Create and fill a data set
Dim datBookInfo As DataSet = New DataSet
oDataAdapterPubs.Fill(datBookInfo, "Publishers")
oDataAdapterTitles.Fill(datBookInfo, "Titles")
Return datBookInfo

Catch ex As Exception
Finally
oPubConnection.Close()

End Try

End Function

check that if the dataset is populated when there is no PostBack.


If(!Page.IsPostBack)
{
LoadData();
}

Hmm, dont see anything obvious...How are you doing your bind of the dataset to the grid?

Also, since this is a windows project and not a web project (assuming your "I've created a vb windows application" is correct) there will NOT be a page.isPostBack...

Thanks,
MajorCats

Populating a dropdown control

I am trying to populate a drop down on a form with the contents of a
recordset and I am getting the following values in the dropdown
System.Data.DataRowView and not the expected content that should be
appearing in there. I have stepped through the code in debug mode and
examine the value of the recordset, and the right values seem to be there.
Any idea what is causing this and how to fix it so that it does not show up
like this?
.ResetParameters()
.AddParameter("iMRN", OleDb.OleDbType.Integer, ParameterDirection.Input,
ctlHeader.PatientData("PatientMRN"))
'Pull back the list of encounters for the selected patient
If .Execute(.genuSql.StoreProcSelect, "selPatient_Billing") Then
Dim oRow As DataRow
oData = .DbData_DataTable
If .DbData_DataTable.Rows.Count > 0 Then
With drpEnc
.DataSource = oData
.DataBind()
.DataValueField = "id"
.DataTextField = "DateOfService"
End With
End If
Else
Throw New Exception(.ErrorMessage)
End If 'Encounter List
J.Daly
structure:interactive
Ph: 616-364-7423
Fx: 616-364-6941
http://www.structureinteractive.comSe the DataText and DataVauleField properties BEFORE the DataBind().
DataBind() binds your source to your control, setting what to bind after
doesn't work :)
Karl
"Irishmaninusa"
<jdaly@.structuctureinteractive.com.takemeoffifyouwantoemailme> wrote in
message news:u3boxQ3iEHA.2992@.TK2MSFTNGP12.phx.gbl...
> I am trying to populate a drop down on a form with the contents of a
> recordset and I am getting the following values in the dropdown
> System.Data.DataRowView and not the expected content that should be
> appearing in there. I have stepped through the code in debug mode and
> examine the value of the recordset, and the right values seem to be there.
> Any idea what is causing this and how to fix it so that it does not show
up
> like this?
>
>
> .ResetParameters()
> .AddParameter("iMRN", OleDb.OleDbType.Integer, ParameterDirection.Input,
> ctlHeader.PatientData("PatientMRN"))
> 'Pull back the list of encounters for the selected patient
> If .Execute(.genuSql.StoreProcSelect, "selPatient_Billing") Then
> Dim oRow As DataRow
> oData = .DbData_DataTable
>
> If .DbData_DataTable.Rows.Count > 0 Then
> With drpEnc
> .DataSource = oData
> .DataBind()
> .DataValueField = "id"
> .DataTextField = "DateOfService"
> End With
> End If
> Else
> Throw New Exception(.ErrorMessage)
> End If 'Encounter List
>
> --
> J.Daly
> structure:interactive
> Ph: 616-364-7423
> Fx: 616-364-6941
> http://www.structureinteractive.com
>
>
I thought I had did that before and it still didn't work, but I tried it
again and this time it work. Now I have different issue, the stored
procedure I call pulls back date values in order, where the most recent date
is at the top and it goes back in order.
7/28/2004
7/1/2004
6/30/2004
This is the where the stored procedure pulls back the dates, which is
correct. However in the drop down it is being displayed as
7/28/2004
6/30/2004
7/1/2004
Why would this be like this?
"Karl" <karl REMOVE @. REMOVE openmymind REMOVEMETOO . ANDME net> wrote in
message news:OzuKbe3iEHA.636@.TK2MSFTNGP12.phx.gbl...
> Se the DataText and DataVauleField properties BEFORE the DataBind().
> DataBind() binds your source to your control, setting what to bind after
> doesn't work :)
> Karl
> "Irishmaninusa"
> <jdaly@.structuctureinteractive.com.takemeoffifyouwantoemailme> wrote in
> message news:u3boxQ3iEHA.2992@.TK2MSFTNGP12.phx.gbl...
there.
> up
>
I honestly don't know. I can see that you are using OLEdbClient which I'm
no expert at. Are these Date fields or string/varchar fields? you may want
to start a new thread asking this question and identifying the
database/query/schema so that someone better suited will help.
Karl
"Irishmaninusa"
<jdaly@.structuctureinteractive.com.takemeoffifyouwantoemailme> wrote in
message news:e2sIEo3iEHA.536@.TK2MSFTNGP11.phx.gbl...
> I thought I had did that before and it still didn't work, but I tried it
> again and this time it work. Now I have different issue, the stored
> procedure I call pulls back date values in order, where the most recent
date
> is at the top and it goes back in order.
> 7/28/2004
> 7/1/2004
> 6/30/2004
> This is the where the stored procedure pulls back the dates, which is
> correct. However in the drop down it is being displayed as
>
> 7/28/2004
> 6/30/2004
> 7/1/2004
> Why would this be like this?
> "Karl" <karl REMOVE @. REMOVE openmymind REMOVEMETOO . ANDME net> wrote in
> message news:OzuKbe3iEHA.636@.TK2MSFTNGP12.phx.gbl...
> there.
show
ParameterDirection.Input,
>
Thanks Karl, I will see what turns up. Thank you for your help to my earlier
issue.
"Karl" <karl REMOVE @. REMOVE openmymind REMOVEMETOO . ANDME net> wrote in
message news:umG6hJ4iEHA.1376@.TK2MSFTNGP11.phx.gbl...
> I honestly don't know. I can see that you are using OLEdbClient which I'm
> no expert at. Are these Date fields or string/varchar fields? you may
want
> to start a new thread asking this question and identifying the
> database/query/schema so that someone better suited will help.
> Karl
> "Irishmaninusa"
> <jdaly@.structuctureinteractive.com.takemeoffifyouwantoemailme> wrote in
> message news:e2sIEo3iEHA.536@.TK2MSFTNGP11.phx.gbl...
> date
in
after
in
and
> show
> ParameterDirection.Input,
>

Populating a dropdown control

I am trying to populate a drop down on a form with the contents of a
recordset and I am getting the following values in the dropdown

System.Data.DataRowView and not the expected content that should be
appearing in there. I have stepped through the code in debug mode and
examine the value of the recordset, and the right values seem to be there.

Any idea what is causing this and how to fix it so that it does not show up
like this?

..ResetParameters()

..AddParameter("iMRN", OleDb.OleDbType.Integer, ParameterDirection.Input,
ctlHeader.PatientData("PatientMRN"))

'Pull back the list of encounters for the selected patient

If .Execute(.genuSql.StoreProcSelect, "selPatient_Billing") Then

Dim oRow As DataRow

oData = .DbData_DataTable

If .DbData_DataTable.Rows.Count > 0 Then

With drpEnc

..DataSource = oData

..DataBind()

..DataValueField = "id"

..DataTextField = "DateOfService"

End With

End If

Else

Throw New Exception(.ErrorMessage)

End If 'Encounter List

--
J.Daly
structure:interactive
Ph: 616-364-7423
Fx: 616-364-6941

http://www.structureinteractive.comSe the DataText and DataVauleField properties BEFORE the DataBind().

DataBind() binds your source to your control, setting what to bind after
doesn't work :)

Karl

"Irishmaninusa"
<jdaly@.structuctureinteractive.com.takemeoffifyouwa ntoemailme> wrote in
message news:u3boxQ3iEHA.2992@.TK2MSFTNGP12.phx.gbl...
> I am trying to populate a drop down on a form with the contents of a
> recordset and I am getting the following values in the dropdown
> System.Data.DataRowView and not the expected content that should be
> appearing in there. I have stepped through the code in debug mode and
> examine the value of the recordset, and the right values seem to be there.
> Any idea what is causing this and how to fix it so that it does not show
up
> like this?
>
>
> .ResetParameters()
> .AddParameter("iMRN", OleDb.OleDbType.Integer, ParameterDirection.Input,
> ctlHeader.PatientData("PatientMRN"))
> 'Pull back the list of encounters for the selected patient
> If .Execute(.genuSql.StoreProcSelect, "selPatient_Billing") Then
> Dim oRow As DataRow
> oData = .DbData_DataTable
>
> If .DbData_DataTable.Rows.Count > 0 Then
> With drpEnc
> .DataSource = oData
> .DataBind()
> .DataValueField = "id"
> .DataTextField = "DateOfService"
> End With
> End If
> Else
> Throw New Exception(.ErrorMessage)
> End If 'Encounter List
>
> --
> J.Daly
> structure:interactive
> Ph: 616-364-7423
> Fx: 616-364-6941
> http://www.structureinteractive.com
I thought I had did that before and it still didn't work, but I tried it
again and this time it work. Now I have different issue, the stored
procedure I call pulls back date values in order, where the most recent date
is at the top and it goes back in order.

7/28/2004
7/1/2004
6/30/2004

This is the where the stored procedure pulls back the dates, which is
correct. However in the drop down it is being displayed as

7/28/2004
6/30/2004
7/1/2004

Why would this be like this?

"Karl" <karl REMOVE @. REMOVE openmymind REMOVEMETOO . ANDME net> wrote in
message news:OzuKbe3iEHA.636@.TK2MSFTNGP12.phx.gbl...
> Se the DataText and DataVauleField properties BEFORE the DataBind().
> DataBind() binds your source to your control, setting what to bind after
> doesn't work :)
> Karl
> "Irishmaninusa"
> <jdaly@.structuctureinteractive.com.takemeoffifyouwa ntoemailme> wrote in
> message news:u3boxQ3iEHA.2992@.TK2MSFTNGP12.phx.gbl...
> > I am trying to populate a drop down on a form with the contents of a
> > recordset and I am getting the following values in the dropdown
> > System.Data.DataRowView and not the expected content that should be
> > appearing in there. I have stepped through the code in debug mode and
> > examine the value of the recordset, and the right values seem to be
there.
> > Any idea what is causing this and how to fix it so that it does not show
> up
> > like this?
> > .ResetParameters()
> > .AddParameter("iMRN", OleDb.OleDbType.Integer, ParameterDirection.Input,
> > ctlHeader.PatientData("PatientMRN"))
> > 'Pull back the list of encounters for the selected patient
> > If .Execute(.genuSql.StoreProcSelect, "selPatient_Billing") Then
> > Dim oRow As DataRow
> > oData = .DbData_DataTable
> > If .DbData_DataTable.Rows.Count > 0 Then
> > With drpEnc
> > .DataSource = oData
> > .DataBind()
> > .DataValueField = "id"
> > .DataTextField = "DateOfService"
> > End With
> > End If
> > Else
> > Throw New Exception(.ErrorMessage)
> > End If 'Encounter List
> > --
> > J.Daly
> > structure:interactive
> > Ph: 616-364-7423
> > Fx: 616-364-6941
> > http://www.structureinteractive.com
I honestly don't know. I can see that you are using OLEdbClient which I'm
no expert at. Are these Date fields or string/varchar fields? you may want
to start a new thread asking this question and identifying the
database/query/schema so that someone better suited will help.

Karl

"Irishmaninusa"
<jdaly@.structuctureinteractive.com.takemeoffifyouwa ntoemailme> wrote in
message news:e2sIEo3iEHA.536@.TK2MSFTNGP11.phx.gbl...
> I thought I had did that before and it still didn't work, but I tried it
> again and this time it work. Now I have different issue, the stored
> procedure I call pulls back date values in order, where the most recent
date
> is at the top and it goes back in order.
> 7/28/2004
> 7/1/2004
> 6/30/2004
> This is the where the stored procedure pulls back the dates, which is
> correct. However in the drop down it is being displayed as
>
> 7/28/2004
> 6/30/2004
> 7/1/2004
> Why would this be like this?
> "Karl" <karl REMOVE @. REMOVE openmymind REMOVEMETOO . ANDME net> wrote in
> message news:OzuKbe3iEHA.636@.TK2MSFTNGP12.phx.gbl...
> > Se the DataText and DataVauleField properties BEFORE the DataBind().
> > DataBind() binds your source to your control, setting what to bind after
> > doesn't work :)
> > Karl
> > "Irishmaninusa"
> > <jdaly@.structuctureinteractive.com.takemeoffifyouwa ntoemailme> wrote in
> > message news:u3boxQ3iEHA.2992@.TK2MSFTNGP12.phx.gbl...
> > > I am trying to populate a drop down on a form with the contents of a
> > > recordset and I am getting the following values in the dropdown
> > > > System.Data.DataRowView and not the expected content that should be
> > > appearing in there. I have stepped through the code in debug mode and
> > > examine the value of the recordset, and the right values seem to be
> there.
> > > > Any idea what is causing this and how to fix it so that it does not
show
> > up
> > > like this?
> > > > > > > > .ResetParameters()
> > > > .AddParameter("iMRN", OleDb.OleDbType.Integer,
ParameterDirection.Input,
> > > ctlHeader.PatientData("PatientMRN"))
> > > > 'Pull back the list of encounters for the selected patient
> > > > If .Execute(.genuSql.StoreProcSelect, "selPatient_Billing") Then
> > > > Dim oRow As DataRow
> > > > oData = .DbData_DataTable
> > > > > > If .DbData_DataTable.Rows.Count > 0 Then
> > > > With drpEnc
> > > > .DataSource = oData
> > > > .DataBind()
> > > > .DataValueField = "id"
> > > > .DataTextField = "DateOfService"
> > > > End With
> > > > End If
> > > > Else
> > > > Throw New Exception(.ErrorMessage)
> > > > End If 'Encounter List
> > > > > --
> > > J.Daly
> > > structure:interactive
> > > Ph: 616-364-7423
> > > Fx: 616-364-6941
> > > > http://www.structureinteractive.com
> > >
Thanks Karl, I will see what turns up. Thank you for your help to my earlier
issue.

"Karl" <karl REMOVE @. REMOVE openmymind REMOVEMETOO . ANDME net> wrote in
message news:umG6hJ4iEHA.1376@.TK2MSFTNGP11.phx.gbl...
> I honestly don't know. I can see that you are using OLEdbClient which I'm
> no expert at. Are these Date fields or string/varchar fields? you may
want
> to start a new thread asking this question and identifying the
> database/query/schema so that someone better suited will help.
> Karl
> "Irishmaninusa"
> <jdaly@.structuctureinteractive.com.takemeoffifyouwa ntoemailme> wrote in
> message news:e2sIEo3iEHA.536@.TK2MSFTNGP11.phx.gbl...
> > I thought I had did that before and it still didn't work, but I tried it
> > again and this time it work. Now I have different issue, the stored
> > procedure I call pulls back date values in order, where the most recent
> date
> > is at the top and it goes back in order.
> > 7/28/2004
> > 7/1/2004
> > 6/30/2004
> > This is the where the stored procedure pulls back the dates, which is
> > correct. However in the drop down it is being displayed as
> > 7/28/2004
> > 6/30/2004
> > 7/1/2004
> > Why would this be like this?
> > "Karl" <karl REMOVE @. REMOVE openmymind REMOVEMETOO . ANDME net> wrote
in
> > message news:OzuKbe3iEHA.636@.TK2MSFTNGP12.phx.gbl...
> > > Se the DataText and DataVauleField properties BEFORE the DataBind().
> > > > DataBind() binds your source to your control, setting what to bind
after
> > > doesn't work :)
> > > > Karl
> > > > "Irishmaninusa"
> > > <jdaly@.structuctureinteractive.com.takemeoffifyouwa ntoemailme> wrote
in
> > > message news:u3boxQ3iEHA.2992@.TK2MSFTNGP12.phx.gbl...
> > > > I am trying to populate a drop down on a form with the contents of a
> > > > recordset and I am getting the following values in the dropdown
> > > > > > System.Data.DataRowView and not the expected content that should be
> > > > appearing in there. I have stepped through the code in debug mode
and
> > > > examine the value of the recordset, and the right values seem to be
> > there.
> > > > > > Any idea what is causing this and how to fix it so that it does not
> show
> > > up
> > > > like this?
> > > > > > > > > > > > > > .ResetParameters()
> > > > > > .AddParameter("iMRN", OleDb.OleDbType.Integer,
> ParameterDirection.Input,
> > > > ctlHeader.PatientData("PatientMRN"))
> > > > > > 'Pull back the list of encounters for the selected patient
> > > > > > If .Execute(.genuSql.StoreProcSelect, "selPatient_Billing") Then
> > > > > > Dim oRow As DataRow
> > > > > > oData = .DbData_DataTable
> > > > > > > > > > If .DbData_DataTable.Rows.Count > 0 Then
> > > > > > With drpEnc
> > > > > > .DataSource = oData
> > > > > > .DataBind()
> > > > > > .DataValueField = "id"
> > > > > > .DataTextField = "DateOfService"
> > > > > > End With
> > > > > > End If
> > > > > > Else
> > > > > > Throw New Exception(.ErrorMessage)
> > > > > > End If 'Encounter List
> > > > > > > > --
> > > > J.Daly
> > > > structure:interactive
> > > > Ph: 616-364-7423
> > > > Fx: 616-364-6941
> > > > > > http://www.structureinteractive.com
> > > > > > > >

Friday, March 16, 2012

Populating a Dropdownlist from a SQL table

Hello guys, I am trying to populate a ddlist on my form from a sql table, but am having trouble coming up with the code.
Here is what i got so far. Im not sure what goes after the read? Thanks you very much.

Sub GetCauseofLoss()

Dim connAs SqlClient.SqlConnection
Dim cmdAs SqlClient.SqlCommand

Dim drAs SqlClient.SqlDataReader

Dim intFieldAsInteger

conn =New SqlClient.SqlConnection

conn.ConnectionString = Replace(Application("ConnectStage"), "Driver={SQL Server}; ", "")

cmd = conn.CreateCommand

conn.Open()

cmd.CommandText = "SELECT * FROM CauseOfLoss"

dr = cmd.ExecuteReader

While dr.Read

dgddLossCode.SelectedValue &= vbNewLine

For intField = 0To dr.FieldCount - 1

?????

Next

EndWhile

dr.Close()

conn.Close()

EndSub

' Assume myDDL is an established web control
Dim myDS as DataSet
' Populate DataSet however you want.
Dim currRecord as DataRow
myDDL.Items.Add(new ListItem("", "blank")) ' Just addin
for each currRecord in myDS.Tables(0).Rows
myDDL.Items.add(new ListItem(currRecord(0)))
next
The index in parenthesis after Tables can be replaced with a string of a table name you proved.
The index in parenthesis after currRecord can be replaced with a string of a column name you proved or the name of the column from the database.
I haven't used DataReader before, thus my example above with a DataSet. Looking at the documentation for it, you would do something similar (and in this case, probably easier).

While dr.Read()
dgddLossCode.Items.Add(new ListItem(dr.Item(COLUMN_INDEX_OR_NAME_HERE)) ' assuming that is you DropDownList
End While
The above example is assuming you only want 1 column. If you want multiple columns from the same row, you can name each column individually, or you can iterate through them or use a method of the class. You can find those athttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdatasqlclientsqldatareadermemberstopic.asp
If you do that, use a String variable and then add the String to the DropDownList


check this

The table Cause of Loss has a Loss _Code, and a Loss_Description. I would need to populate the ddlist with both columns. I also didnt mention that this ddlist is part of a datagrid. Thank you very much guys for your help. Does this look OK?

Sub GetCauseofLoss()

Dim conn As SqlClient.SqlConnection
Dim cmd As SqlClient.SqlCommand
Dim myDS as DataSet
Dim currRecord as DataRow

Dim dr As SqlClient.SqlDataReader
Dim intField As Integer
conn = New SqlClient.SqlConnection
conn.ConnectionString = Replace(Application("ConnectStage"), "Driver={SQL Server}; ", "")
cmd = conn.CreateCommand
conn.Open()

cmd.CommandText = "SELECT * FROM CauseOfLoss"

dr = cmd.ExecuteReader
While dr.Read

for each currRecord in myDS.Tables(0).Rows
dgddLossCode.Items.Add(new ListItem(dr.Item(Loss_Code))
dgddLossCode.Items.Add(new ListItem(dr.Item(Loss_Description))
next

End While
dr.Close()
conn.Close()

End Sub


Each add call on the dropdownlist.item will add a new list item. What you need to do is similar, but more like
Dim strToAdd as String
While dr.Read
strToAdd = ""
for each currRecord in myDS.Tables(0).Rows
strToAdd &= dr.Item(Loss_Code)
strToAdd &= dr.Item(Loss_Description)
dgddLossCode.Items.Add(strToAdd)
next
End While
You may want to space them somehow, but I'm not sure the best method on that. As for the ddl being in a DataGrid, I'm not sure that would change this part of the code. It's still DropDownList, just encapsulated within a DataGrid.

vin1127 wrote:

Sub GetCauseofLoss()

Dim conn As SqlClient.SqlConnection
Dim cmd As SqlClient.SqlCommand
Dim myDS as DataSet
Dim currRecord as DataRow

Dim dr As SqlClient.SqlDataReader
Dim intField As Integer
conn = New SqlClient.SqlConnection
conn.ConnectionString = Replace(Application("ConnectStage"), "Driver={SQL Server}; ", "")
cmd = conn.CreateCommand
conn.Open()

cmd.CommandText = "SELECT * FROM CauseOfLoss"

dr = cmd.ExecuteReader
While dr.Read

for each currRecord in myDS.Tables(0).Rows
dgddLossCode.Items.Add(new ListItem(dr.Item(Loss_Code))
dgddLossCode.Items.Add(new ListItem(dr.Item(Loss_Description))
next


Hi, your DataSet was not filled and it is empty and uninstantiated, your foreach loop would not run. Try this
protected void dgrd_ItemDataBound(Object sender, DataGridItemEventArgs e)
{
// if in <EditItemTemplate>, use ListItemType.EditItem
if(e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{

// open connection here
// DataSet declaration

// retrieve the fields needed only
string strSQL = "SELECT Loss_Code, Loss_Description FROM CauseOfLoss";
SqlDataAdapter daCOL = new SqlDataAdapter(strSQL,conn);

daCOL.Fill(myDS,"COL");
DataColumn dcol = new DataColumn();
dcol.ColumnName = "CompositeCol";
dcol.ColumnType = System.Type.GetType("System.String");
dcol.Expression = "Loss_Code + ' - ' + Loss_Description";
myDS.Tables["COL"].Columns.Add(dcol);
// locate DDL in DataGrid
DropDownList ddl = (DropDownList)e.Item.FindControl("ddlIDInGrid");
ddl.DataSource = myDS.Tables["COL"];
ddl.DataTextField = "CompositeCol";
ddl.DataValueField = "Loss_Code";
ddl.DataBind();
}
}


Hope this helps...

vin1127 wrote:

The table Cause of Loss has a Loss _Code, and a Loss_Description. I would need to populate the ddlist with both columns. I also didnt mention that this ddlist is part of a datagrid. Thank you very much guys for your help. Does this look OK?

Sub GetCauseofLoss()

Dim conn As SqlClient.SqlConnection
Dim cmd As SqlClient.SqlCommand
Dim myDS as DataSet
Dim currRecord as DataRow

Dim dr As SqlClient.SqlDataReader
Dim intField As Integer
conn = New SqlClient.SqlConnection
conn.ConnectionString = Replace(Application("ConnectStage"), "Driver={SQL Server}; ", "")
cmd = conn.CreateCommand
conn.Open()

cmd.CommandText = "SELECT * FROM CauseOfLoss"

dr = cmd.ExecuteReader
While dr.Read

for each currRecord in myDS.Tables(0).Rows
dgddLossCode.Items.Add(new ListItem(dr.Item(Loss_Code))
dgddLossCode.Items.Add(new ListItem(dr.Item(Loss_Description))
next

End While
dr.Close()
conn.Close()

End Sub



Your code should be this.

Sub GetCauseofLoss()

Dim conn As SqlClient.SqlConnection
Dim cmd As SqlClient.SqlCommand
Dim myDS as DataSet
Dim currRecord as DataRow

Dim dr As SqlClient.SqlDataReader
Dim intField As Integer
conn = New SqlClient.SqlConnection
conn.ConnectionString = Replace(Application("ConnectStage"), "Driver={SQL Server}; ", "")
cmd = conn.CreateCommand
conn.Open()

cmd.CommandText = "SELECT * FROM CauseOfLoss"

dr = cmd.ExecuteReader
While dr.Read

for each currRecord in myDS.Tables(0).Rows
dgddLossCode.Items.Add(new ListItem(dr.Item("Loss_Code"),dr.Item("Loss_Description"))
next

End While
dr.Close()
conn.Close()

End Sub


for each currRecord in myDS.Tables(0).Rows
dgddLossCode.Items.Add(new ListItem(dr.Item("Loss_Code"),dr.Item("Loss_Description"))
next
The above will actually add a new ListItem to your DDL with a Text of the value in Loss_Code and a Value of "Loss_Description". If this is what you want, thent that is correct. If you want them to both be added, you'll need to make them 1 string, then add that string. On a note, if you only supply on parameter to ListItem, it is made both the Text and Value property.

Populating a GridView in code

I am looking for examples for populating a GridView in code.
I have a GridView that I want to show unbound when the form opens and then
filled with different collections of data based on options the user selects.
Any help is greatly appreciated.The idea is that based on the user selection, you would databind the grid to
different datasources (collections). You better ask specific questions as
you go.
Eliyahu Goldin,
Software Developer & Consultant
Microsoft MVP [ASP.NET]
"Greg Smith" <gjs@.umn.edu> wrote in message
news:%23WddSY2$GHA.3560@.TK2MSFTNGP03.phx.gbl...
>I am looking for examples for populating a GridView in code.
> I have a GridView that I want to show unbound when the form opens and then
> filled with different collections of data based on options the user
> selects.
>
> Any help is greatly appreciated.
>

Populating a GridView in code

I am looking for examples for populating a GridView in code.

I have a GridView that I want to show unbound when the form opens and then
filled with different collections of data based on options the user selects.

Any help is greatly appreciated.The idea is that based on the user selection, you would databind the grid to
different datasources (collections). You better ask specific questions as
you go.

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

"Greg Smith" <gjs@.umn.eduwrote in message
news:%23WddSY2$GHA.3560@.TK2MSFTNGP03.phx.gbl...

Quote:

Originally Posted by

>I am looking for examples for populating a GridView in code.
>
I have a GridView that I want to show unbound when the form opens and then
filled with different collections of data based on options the user
selects.
>
>
Any help is greatly appreciated.
>

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 + "'";