Showing posts with label stored. Show all posts
Showing posts with label stored. Show all posts

Saturday, March 24, 2012

Populate Labels with DataSet in code

I have several Label controls in my page and a stored procedure that always return 1 row. I want to call the same stored procedure with different parameter. Can anybody who me how to do this?

I have a function that contains:

 DataSet objDs =new DataSet();
System.Data.SqlClient.SqlConnection myConnection =new System.Data.SqlClient.SqlConnection(
System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

System.Data.SqlClient.SqlDataAdapter cmd;
cmd =new System.Data.SqlClient.SqlDataAdapter("sp_getCounter1", myConnection);

cmd.SelectCommand.CommandType = CommandType.StoredProcedure;
cmd.SelectCommand.Parameters.Add(
new SqlParameter("@dotnet.itags.org.param1", mode));
DataTable dtMasterListe =new DataTable("mytable");

myConnection.Open();
cmd.Fill(objDs);

With the above code it is easy to e.g bind to datagrid, but I want to achiveve the following Label1.Text = objDs.getstring(etc).

Any clues?

public string FunctionName(){using (SqlConnection cn =new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString)) { SqlCommand cmd =new SqlCommand("StoredProcedureName", cn); cmd.CommandType = CommandType.StoredProcedure;// Add parameters if needed cn.Open();return (string)ExecuteScalar(cmd); }}void Page_Load(){ Label1.Text = FunctionName()}

This is what I usually do:

If you already sure the dataset only contains 1 table and 1 row only, then you can use the following to get the data you want:
Label1.Text = ds.Tables[0].Rows[0][0].ToString();

If you know the table name returned in the dataset, you can also pass in the tablename:
Label1.Text = ds.Tables["tablename"].Rows[0][0].ToString();

It will even be better if you can specify the column name:
Label1.Text = ds.Tables["tablename"].Rows[0]["Name"].ToString();

I usually check if the number of tables & rows > 0 then only get the value:
if ((ds.Tables.Count == 0) && (ds.Tables["tablename"].Rows.Count == 0))

Hope this helps. ^_^



Hi,

If you know that your stored procedure will return only one row all the time, then go for theExcecuteScalar method.


Works perfect!

Had to make a minor change:


int ret = (int)cmd.ExecuteScalar();
return ret.ToString();

to make ExecuteScalar to work.


Thanks.

populate text box from sql

when my page opens how i can i auto-populate a text box from a value that is passed from a stored proc?On your Form_Load, grab the data from the stored proc, set your textbox equal to the value it returns.

Wednesday, March 21, 2012

Populating a data grid with a stored procudure w/parameters

All,

I'm trying to populate a datagrid with a data adapter that uses a stored
procedure with a parameter. I get the below error when I run my code
(as seen below). Any hints?

If I delete the .value = "Business Acumen" at the end of the add
parameters statement & put the below code on a different row, the error
goes away, but I get back an empty dataset.

Me.cmdUYP.Parameters("@dotnet.itags.org.web_competency_name").Value = "Business Acumen"

Error Msg:
The SqlParameterCollection only accepts non-null SqlParameter type
objects, not Boolean objects.

My Code:

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Text.RegularExpressions
Imports System.Text

Public Class UYP_Class
Inherits System.Web.UI.Page
Protected WithEvents btnFLMClose As System.Web.UI.WebControls.Button
Dim previousCat As String
Dim previousComp As String
Protected WithEvents linkIntelU As
System.Web.UI.WebControls.HyperLink
Protected WithEvents Image1 As System.Web.UI.WebControls.Image
Protected WithEvents btnClose As System.Web.UI.WebControls.Button
Protected WithEvents lnkIntelLibrary As
System.Web.UI.WebControls.HyperLink
Protected WithEvents lnkBuyOnline As
System.Web.UI.WebControls.HyperLink
Protected WithEvents conUYP As System.Data.SqlClient.SqlConnection
Protected WithEvents lblError As System.Web.UI.WebControls.Label
Protected WithEvents daUYP As System.Data.SqlClient.SqlDataAdapter
Protected WithEvents cmdUYP As System.Data.SqlClient.SqlCommand
Protected WithEvents DsUYP1 As FDO.dsUYP
Protected WithEvents lnkAllCurric As
System.Web.UI.WebControls.HyperLink
Protected WithEvents lnkHelp As System.Web.UI.WebControls.HyperLink
Protected WithEvents dgUYP As System.Web.UI.WebControls.DataGrid
Protected WithEvents btnExportExcel As
System.Web.UI.WebControls.Button

#Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub
InitializeComponent()
Me.conUYP = New System.Data.SqlClient.SqlConnection()
Me.daUYP = New System.Data.SqlClient.SqlDataAdapter()
Me.cmdUYP = New System.Data.SqlClient.SqlCommand()
Me.DsUYP1 = New FDO.dsUYP()
CType(Me.DsUYP1,
System.ComponentModel.ISupportInitialize).BeginIni t()
'
'conUYP
'
Me.conUYP.ConnectionString = "data source=OREA2SQL017;initial
catalog=Fin_Trng_DB;password=abcd$1234;persist se" & _
"curity info=True;user id=FinTrngUserGrp"
'
'daUYP
'
Me.daUYP.SelectCommand = Me.cmdUYP
'
'cmdUYP
'
Me.cmdUYP.CommandText = "dbo.[prc_uyp_curriculum]"
Me.cmdUYP.CommandType = System.Data.CommandType.StoredProcedure
Me.cmdUYP.Connection = Me.conUYP
Me.cmdUYP.Parameters.Add(New
System.Data.SqlClient.SqlParameter("@dotnet.itags.org.web_competency_name",
System.Data.SqlDbType.NVarChar, 50).Value = "Business Acumen")

'
'DsUYP1
'
Me.DsUYP1.DataSetName = "dsUYP"
Me.DsUYP1.Locale = New System.Globalization.CultureInfo("en-US")
Me.DsUYP1.Namespace = "http://www.tempuri.org/dsUYP.xsd"
CType(Me.DsUYP1,
System.ComponentModel.ISupportInitialize).EndInit( )

End Sub

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub

#End Region

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
Try
'Me.cmdUYP.Parameters("web_competency_name").Value =
"Business Acumen"
daUYP.Fill(DsUYP1, "prc_uyp_curriculum")
If Not IsPostBack Then
dgUYP.DataSource =
DsUYP1._dbo_prc_uyp_curriculum.DefaultView()
dgUYP.DataBind()
End If
End Sub
End Class

Machelle Chandler
Intel Corporation
Beginning .NET developer
Thanks in advance for the help!

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!Hi Machelle. Try changing this
Me.cmdUYP.Parameters.Add(New
System.Data.SqlClient.SqlParameter("@.web_competency_name",
System.Data.SqlDbType.NVarChar, 50).Value = "Business Acumen")

for
Me.cmdUYP.Parameters.Add("@.web_competency_name",
System.Data.SqlDbType.NVarChar, 50).Value = "Business Acumen";

"Machelle Chandler" <machelle.a.chandler@.intel.com> wrote in message
news:#fF2buClDHA.2232@.TK2MSFTNGP09.phx.gbl...
> All,
> I'm trying to populate a datagrid with a data adapter that uses a stored
> procedure with a parameter. I get the below error when I run my code
> (as seen below). Any hints?
> If I delete the .value = "Business Acumen" at the end of the add
> parameters statement & put the below code on a different row, the error
> goes away, but I get back an empty dataset.
> Me.cmdUYP.Parameters("@.web_competency_name").Value = "Business Acumen"
> Error Msg:
> The SqlParameterCollection only accepts non-null SqlParameter type
> objects, not Boolean objects.
>
> My Code:
> Imports System
> Imports System.Data
> Imports System.Data.SqlClient
> Imports System.Text.RegularExpressions
> Imports System.Text
>
> Public Class UYP_Class
> Inherits System.Web.UI.Page
> Protected WithEvents btnFLMClose As System.Web.UI.WebControls.Button
> Dim previousCat As String
> Dim previousComp As String
> Protected WithEvents linkIntelU As
> System.Web.UI.WebControls.HyperLink
> Protected WithEvents Image1 As System.Web.UI.WebControls.Image
> Protected WithEvents btnClose As System.Web.UI.WebControls.Button
> Protected WithEvents lnkIntelLibrary As
> System.Web.UI.WebControls.HyperLink
> Protected WithEvents lnkBuyOnline As
> System.Web.UI.WebControls.HyperLink
> Protected WithEvents conUYP As System.Data.SqlClient.SqlConnection
> Protected WithEvents lblError As System.Web.UI.WebControls.Label
> Protected WithEvents daUYP As System.Data.SqlClient.SqlDataAdapter
> Protected WithEvents cmdUYP As System.Data.SqlClient.SqlCommand
> Protected WithEvents DsUYP1 As FDO.dsUYP
> Protected WithEvents lnkAllCurric As
> System.Web.UI.WebControls.HyperLink
> Protected WithEvents lnkHelp As System.Web.UI.WebControls.HyperLink
> Protected WithEvents dgUYP As System.Web.UI.WebControls.DataGrid
> Protected WithEvents btnExportExcel As
> System.Web.UI.WebControls.Button
> #Region " Web Form Designer Generated Code "
> 'This call is required by the Web Form Designer.
> <System.Diagnostics.DebuggerStepThrough()> Private Sub
> InitializeComponent()
> Me.conUYP = New System.Data.SqlClient.SqlConnection()
> Me.daUYP = New System.Data.SqlClient.SqlDataAdapter()
> Me.cmdUYP = New System.Data.SqlClient.SqlCommand()
> Me.DsUYP1 = New FDO.dsUYP()
> CType(Me.DsUYP1,
> System.ComponentModel.ISupportInitialize).BeginIni t()
> '
> 'conUYP
> '
> Me.conUYP.ConnectionString = "data source=OREA2SQL017;initial
> catalog=Fin_Trng_DB;password=abcd$1234;persist se" & _
> "curity info=True;user id=FinTrngUserGrp"
> '
> 'daUYP
> '
> Me.daUYP.SelectCommand = Me.cmdUYP
> '
> 'cmdUYP
> '
> Me.cmdUYP.CommandText = "dbo.[prc_uyp_curriculum]"
> Me.cmdUYP.CommandType = System.Data.CommandType.StoredProcedure
> Me.cmdUYP.Connection = Me.conUYP
> Me.cmdUYP.Parameters.Add(New
> System.Data.SqlClient.SqlParameter("@.web_competency_name",
> System.Data.SqlDbType.NVarChar, 50).Value = "Business Acumen")
> '
> 'DsUYP1
> '
> Me.DsUYP1.DataSetName = "dsUYP"
> Me.DsUYP1.Locale = New System.Globalization.CultureInfo("en-US")
> Me.DsUYP1.Namespace = "http://www.tempuri.org/dsUYP.xsd"
> CType(Me.DsUYP1,
> System.ComponentModel.ISupportInitialize).EndInit( )
> End Sub
> Private Sub Page_Init(ByVal sender As System.Object, ByVal e As
> System.EventArgs) Handles MyBase.Init
> 'CODEGEN: This method call is required by the Web Form Designer
> 'Do not modify it using the code editor.
> InitializeComponent()
> End Sub
> #End Region
> Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
> System.EventArgs) Handles MyBase.Load
> 'Put user code to initialize the page here
> Try
> 'Me.cmdUYP.Parameters("web_competency_name").Value =
> "Business Acumen"
> daUYP.Fill(DsUYP1, "prc_uyp_curriculum")
> If Not IsPostBack Then
> dgUYP.DataSource =
> DsUYP1._dbo_prc_uyp_curriculum.DefaultView()
> dgUYP.DataBind()
> End If
> End Sub
> End Class
> Machelle Chandler
> Intel Corporation
> Beginning .NET developer
> Thanks in advance for the help!
> *** Sent via Developersdex http://www.developersdex.com ***
> Don't just participate in USENET...get rewarded for it!

populating a datagrid from a parameterized procedure during page load

I have a datagrid control on my page populated from a parameterized stored procedure. The parameter comes from a label control on my page as seen below. I cannot get the grid to populate. Any suggestions?

Dim LocalIP = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If LocalIP =""Then
LocalIP = Request.ServerVariables("REMOTE_ADDR")
EndIf
Label1.Text = LocalIP

TIA <JP>

Hi paskettj,

first check if Label1.text has been assigned to the correct value(mean, what's the value of " LocalIP" ? you can use debug, or response.write to monitor it);

secondly,check if your sotred procedure has returned the correct data;

and the third, pls check if you have use datagrid correctly. To get your datagrid control populated with corresponding data,First, you need to set the correct DataSource or DataSourceID, then call the Databind() method. It doesn't matter where you get your data from(whether it's from a table,backend database, from parameterized stored procedure...etc).

for more detailed information, i suggest you reading some material by clicking the following links:

http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.basedatalist.datasource(VS.71).aspx (the sample within this page should help u use datagrid)

http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.datagrid.aspx (to a overview of datagird class)

hope my suggestion helps :)

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 using a SQL Stored Procedure

Hello All
I posted this question yesterday but I do not see it in the list, and I cannot search and locate it.

I am rather new to coding in ASP.NET. However, I have been coding with Classic ASP for many years. Please be patient with me and my seemingly simple questions

I am in need of some help with Populating a Drop Down List is ASp.NET using C#. I want to be able to populate a drop down list with the ID as the value and the Text as the text shown by calling a SQL stored procedure. If possible, can you give me an example and comment what the steps are.

After much searching yesterday, I found a good example using access. But this is not what I needed. However, it did get me started with the concept.

And another question. How would I code to see the value choosen? My web forms contain mostly drop down list for items such as: state names, postal codes, area codes, dates, times, etc... Just about anything that I can use a DDL, I use it. Saves so much in the error checking.

Thank you in advance for your time.
Andrew
SQL DBATheres a few steps involved in getting data to be present on a page.

First for your application you'll need to create a DataReader object to interact with your SQLCommand which is your stored procedure. (research on how to implement a DataReader)

Then once you have data in your DataReader, you can bind it do the DDL like so:

ddl.DataSource = YourDataReaderName
ddl.DataValueField = "FieldNameofYourChoice" from your DataReader
ddl.DataTextFiled = "FiledNameofYourchoice" from your DataReader
ddl.DataBind

Basically that's it
Thank you
I was hoping to get more of a step by step instruction.
I am having alot of trouble making the database connection. I am seeing so many different types and ways of doing the same thing, that it is getting very confusing. Some inside the aspx page and some in the cs page. I would like to use the code behind cs page.

Any sites out there tell how to do that? And give good examples.

I used to use that same signature many years ago.

Thanks
Andrew

populating a dropdown with stored procedure in ms access

hallo,

I'm trying to populate a dropdown by using a stored procedure in an access db, but what I get is completely empty dropdown. Am I doing something wrong?

this is the code I'm using:

code-behind:

Private function BindArchive()
dim myConnection as new OleDBConnection ("Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=C:\inetpub\wwwroot\new1\db.mdb")
dim objCmd_archive as OleDbCommand = new OleDbCommand ("Query1", myConnection)
objCmd_archive.CommandType = CommandType.StoredProcedure
myConnection.Open()
Return objCmd_archive.ExecuteReader()
myConnection.Close()
End Function

dropdown control:

<form runat="server">
<asp:DropDownList id="cbo_archive" DataSource="<%# BindArchive() %>" DataTextField="mes_date" DataTextValue="mes_date" runat="server" />
</form>

thanks for suggestions

I highly recommend against using this function for getting the data. The reason is that you are exiting the function before closing the database, which you should never do and which means that the database won't be closed. You need to assign the DataReader to the DDL's DataSource in your CodeBehind. For example:

Page_Load(...)

...

myConnection.Open()

cbo_archive.DataSource = objCmd_archive.ExecuteReader();

cbo_archive.DataBind();

myConnection.Close.

End

Furthermore, it is best practice to place you database activity within aTry/Catch/Finally block, where you close the database connection in the Finally section.