Build your professional network on facebook via our app Go to app
 
<< Prev  5 of 6 in Topic  Next >>
Topic : SQL Server Programming
  Rate : 
Associated with other topics :
  Rate : 
 
Industry : IT Services
Functional Area : Programming Languages
Activity: Question posted: 12 02 2008 08:50:49 +0000, 7 answers, 1739 views, last activity 07 06 2010 20:18:08 +0000
 
Share
 
 
 
 

Hi all,

 I'm developing a simple project using C#.net 2005 with SQL Server 2000. In my project, I need to retrieve the data from SQL database in my page with the help of stored procedure. I've no idea that how to do?

Please help me.

 
 Top Answer :
Rating : +1 

Create an ASP.NET Project and Add Controls

In this section, you create an ASP.NET project and build the basic user interface. Note that these steps use Microsoft Visual C# .NET code. To create the project, follow these steps:

  1. Click Start, point to Programs, point to Microsoft Visual Studio .NET, and then click Microsoft Visual Studio .NET.
  2. On the Visual Studio .NET Start page, click New Project.
  3. In the New Project dialog box, click Visual C# Projects under Project Types, and then click ASP.NET Web Application under Templates.
  4. In the Name box, type a name for your Web application, and then click OK.
  5. Add the following server controls to the Web Form, and set the properties as they are listed in the table:
    Collapse this tableExpand this table
    ControlID PropertyText Property
    Label lblLastName Type the Author's Last Name:
    TextBox txtLastName %
    Button btnGetAuthors Get Authors
    Label lblRowCount (Row Count)
  6. Drag a DataGrid server control from the toolbox to the Web Form, and then set the Name property to GrdAuthors.
  7. Right-click the grid, and then click Autoformat.
  8. Click Professional 1 for the scheme, and then click OK.

Create the GetAuthorsByLastName Stored Procedure

Use the following Transact-SQL code to create the GetAuthorsByLastName stored procedure:

Use Pubs
Go
Create Procedure GetAuthorsByLastName (@au_lname varchar(40), @RowCount int output)  
as 

select * from authors where au_lname like @au_lname; 

/* @@ROWCOUNT returns the number of rows that are affected by the last statement. */ 
select @RowCount=@@ROWCOUNT
				

This code includes two parameters: @au_lname and @RowCount. The @au_lname parameter is an input parameter that obtains the search string to perform a "like" search in the Authors table. The @RowCount parameter is an output parameter that uses the @@ROWCOUNT variable to obtain the affected rows.

Create and Run the Stored Procedure

To access SQL Server databases, you must import the System.Data.SqlClient namespace, which provides new objects such as the SqlDataReader and the SqlDataAdapter objects. You can use SqlDataReader to read a forward-only stream of rows from a SQL Server database. DataAdapter represents a set of data commands and a database connection that you can use to fill the DataSet object and to update a SQL Server database.

ADO.NET also introduces the DataSet object, which is a memory-resident representation of data that provides a consistent, relational programming model regardless of the data source. The code in this section uses all of these objects.

  1. Double-click the Web Form.
  2. Add the following code (the using directives) to the Declaration section of your Web Form, which appears at the top of the Code window:
    using System.Data;
    using System.Data.SqlClient;
    					
  3. To make sure that the stored procedure exists and to create a new stored procedure, use a SqlCommand object with a SqlDataReader object. You can use SqlCommand to run any SQL commands against the database. Then call the ExecuteReader method of SqlCommand to return SqlDataReader, which contains matching rows for your query.

    Add the following code in the Page_Load event of the Web Form:
    	private void Page_Load(object sender, System.EventArgs e)
    	{
    		// Only run this code the first time the page is loaded.
    		// The code inside the IF statement is skipped when you resubmit the page.
    		if (!IsPostBack)
    		{
    			//Create a connection to the SQL Server; modify the connection string for your environment
    			//SqlConnection MyConnection = new SqlConnection("server=(local);database=pubs;Trusted_Connection=yes");
    			SqlConnection MyConnection = new SqlConnection("server=(local);database=pubs;UID=myUser;PWD=myPassword;");
    
    			// Create a Command object, and then set the connection.
    			// The following SQL statements check whether a GetAuthorsByLastName  
    			// stored procedure already exists.
    			SqlCommand MyCommand = new SqlCommand("select * from sysobjects where id = object_id(N'GetAuthorsByLastName')" +
    			"  and OBJECTPROPERTY(id, N'IsProcedure') = 1", MyConnection);
    
    			// Set the command type that you will run.
    			MyCommand.CommandType = CommandType.Text;
    
    			// Open the connection.
    			MyCommand.Connection.Open();
    
    			// Run the SQL statement, and then get the returned rows to the DataReader.
    			SqlDataReader MyDataReader = MyCommand.ExecuteReader();
    
    			// If any rows are returned, the stored procedure that you are trying 
    			// to create already exists. Therefore, try to create the stored procedure
    			// only if it does not exist.
    			if(!MyDataReader.Read())
    			{
    				MyCommand.CommandText = "create procedure GetAuthorsByLastName" + 
    					" (@au_lname varchar(40), select * from authors where" +
    					" au_lname like @au_lname; select @RowCount=@@ROWCOUNT";
    				MyDataReader.Close();
    				MyCommand.ExecuteNonQuery();
    			}
    			else
    			{
    				MyDataReader.Close();
    			}
    
    			MyCommand.Dispose();  //Dispose of the Command object.
    			MyConnection.Close(); //Close the connection.
    		}
    
    		// Add the event handler to the Button_Click event.
    		this.btnGetAuthors.Click += new System.EventHandler(this.btnGetAuthors_Click);
    	}
    					
  4. Call the stored procedure in the Click event of the btnGetAuthors button, and then use the SqlDataAdapter object to run your stored procedure. You must create parameters for the stored procedure and append it to the Parameters collection of the SqlDataAdapter object.

    Add the following code after the Page_Load event:
    	private void btnGetAuthors_Click(object sender, System.EventArgs e)
    	{
    		//Create a connection to the SQL Server; modify the connection string for your environment.
    		//SqlConnection MyConnection = new SqlConnection("server=(local);database=pubs;Trusted_Connection=yes");
    		SqlConnection MyConnection = new SqlConnection("server=(local);database=pubs;UID=myUser;PWD=myPassword;");
    
    		//Create a DataAdapter, and then provide the name of the stored procedure.
    		SqlDataAdapter MyDataAdapter = new SqlDataAdapter("GetAuthorsByLastName", MyConnection);
    
    		//Set the command type as StoredProcedure.
    		MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
    
    		//Create and add a parameter to Parameters collection for the stored procedure.
    		MyDataAdapter.SelectCommand.Parameters.Add(new SqlParameter("@au_lname", SqlDbType.VarChar, 40));
    
    		//Assign the search value to the parameter.
    		MyDataAdapter.SelectCommand.Parameters["@au_lname"].Value = (txtLastName.Text).Trim();
    
    		//Create and add an output parameter to the Parameters collection. 
    		MyDataAdapter.SelectCommand.Parameters.Add(new SqlParameter("@RowCount", SqlDbType.Int, 4));
    
    		//Set the direction for the parameter. This parameter returns the Rows that are returned.
    		MyDataAdapter.SelectCommand.Parameters["@RowCount"].Direction = ParameterDirection.Output;
    
    		//Create a new DataSet to hold the records.
    		DataSet DS = new DataSet();
    		
    		//Fill the DataSet with the rows that are returned.
    		MyDataAdapter.Fill(DS, "AuthorsByLastName");
    
    		//Get the number of rows returned, and assign it to the Label control.
    		//lblRowCount.Text = DS.Tables(0).Rows.Count().ToString() & " Rows Found!"
    		lblRowCount.Text = MyDataAdapter.SelectCommand.Parameters[1].Value + " Rows Found!";
    
    		//Set the data source for the DataGrid as the DataSet that holds the rows.
    		GrdAuthors.DataSource = DS.Tables["AuthorsByLastName"].DefaultView;
    
    		//NOTE: If you do not call this method, the DataGrid is not displayed!
    		GrdAuthors.DataBind();
    
    		MyDataAdapter.Dispose(); //Dispose the DataAdapter.
    		MyConnection.Close(); //Close the connection.
    	}
    					
  5. In Solution Explorer, right-click the .aspx page, and then click Set as Start Page.
  6. Save the project, and then click Start in Visual Studio .NET. Notice that the project is compiled and that the default page runs.
  7. Type the author's last name in the text box, and then click Get Author. Notice that the stored procedure is called and that the returned rows populate the DataGrid.

    You can provide SQL Server-type search strings such as G%, which returns all the authors by last names that start with the letter "G."

Troubleshooting

 

  • If you cannot connect to the database, make sure that the ConnectionString properly points to the server that is running SQL Server.
  • If you can connect to the database, but if you experience problems when you try to create the stored procedure, make sure that you have the correct permissions to create stored procedures in the database to which you are connecting.


[ Delete ]
[ Edit ]
Report Abuse
by   sameer kamble, IT Manager, indsoft systems  | 04 17 2009 15:04:31 +0000
  Answered by     Shivpraksh Rai, Software Developer, Confidential  | 05 14 2009 04:06:14 +0000
[ Delete ]
[ Edit ]
Not Rated

Hi Dude !

This is a simple way to get Data from SQL server Strore Procedure by passing some Input Based.

-------------1---------------------

CREATE PROCEDURE [dbo].[Login_Employee_GET_SP]  
 ( 
  @M_USER_ID  VARCHAR(10)=NULL,
  @M_PASSWORD VARCHAR(20)=NULL
 ) 
AS 
BEGIN
 
 SELECT EMP_WINDOW_ID,EMP_FIRST_NAME,EMP_LAST_NAME, EMP_EMAIL,
  DESIGNATION,LTRIM(RTRIM(LOCATION)) AS LOCATION ,DEPARTMENT,REPORT_TO,ACCESS
 FROM  TBL_DEL_EMPLOYEE
 WHERE EMP_WINDOW_ID = @M_USER_ID AND EMP_PASSWORD=@M_PASSWORD AND DELETED=0

END 

 

-----------1---------------

-------------2-------------------

1) Cretae a Simple Function This will return DataSet Objects.

public DataSet fncGetPrcgetUserDetails(Hashtable objHashParams)
            { 
              SqlConnection mObjclsConnection = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConStr"]);   // Read Config Vaible

                DataSet mObjDataSet = new DataSet();
                SqlCommand mObjCmd = new SqlCommand();
                SqlDataAdapter sqlAdap = new SqlDataAdapter(mObjCmd);

               try
               {
                   SqlParameter mObjParam =new SqlParameter();
                   mObjCmd.Connection = mObjclsConnection;
                   mObjCmd.CommandText = "Login_Employee_GET_SP";   //Store Procedure Name
                   mObjCmd.CommandType = CommandType.StoredProcedure;

                   if ((objHashParams["UserID"] == null)) //Input Variable
                   {
                       mObjParam = new SqlParameter("@M_USER_ID", DBNull.Value);
                   }
                   else
                   {
                       mObjParam = new SqlParameter("@M_USER_ID", objHashParams["UserID"]);
                   }

                   mObjParam.DbType = DbType.String;
                   mObjCmd.Parameters.Add(mObjParam);
                   mObjParam = null;

                  if ((objHashParams["Password"] == null))  //Input Variable

                   {
                       mObjParam = new SqlParameter("@M_PASSWORD", DBNull.Value);
                   }
                   else
                   {
                       mObjParam = new SqlParameter("@M_PASSWORD", objHashParams["Password"]);
                   }

                   mObjParam.DbType = DbType.String;
                   mObjCmd.Parameters.Add(mObjParam);
                   mObjParam = null;

                   sqlAdap.Fill(mObjDataSet);

                   return mObjDataSet;
               }
               catch (Exception Ex)
               {
                   throw Ex;
               }
               finally
               {
                   mObjclsConnection = null;
               }
                     
        }

-------------2---------------------

 

 

  Answered by     Neeraj Tanwar, Software Developer, weexcel  | 04 07 2009 06:22:32 +0000
[ Delete ]
[ Edit ]
Rating : +1 

using System.data.sqlclient;

using System.data;

sqlcommand sqlcom

sqlconnection sqlcon;

sqlDataAdapter adpcomm;

dataset da=new dataset;

string sqry;

sqry="YourStoredProcedure Name";

Sqlcom=new sqlcommand(sqry,sqlcon);

sqlcom.commandType=commandtype.storedProcedure;

sqlcom.parameters.addWithValue(if Any Parameters u got the Synatax is "@ppp",Value eg 1,a,1.1)

adpcom=new SqldataAdapter(sqlcom)

adpcomm.fill(ds,"tableName)

 

 

 

  Answered by     Rahamadulla , Software Developer, Profiniti Systems  | 03 20 2009 10:06:36 +0000
[ Delete ]
[ Edit ]
Rating : +1 

public Result GetBill(out string BillXML)
        {
            Result retVal;
            retVal.Message = "";
            retVal.Status = false;
            BillXML = null;

            try
            {
                SqlXmlCommand cmd = new SqlXmlCommand(@DataBaseXml);
                cmd.CommandType = SqlXmlCommandType.Sql;
                cmd.CommandText = "exec [GetBill]";
                Stream output = cmd.ExecuteStream();
                StreamReader reader = new StreamReader(output);
                BillXML = reader.ReadToEnd();
                BillXML = "<Admin>" + BillXML + "</Admin>";
                retVal.Status = true;
                return retVal;
            }
            catch (Exception ex)
            {
                Utility.ErrorLog.WriteToFile(errorfile, "GetBill", ex.Message);
                retVal.Status = false;
                return retVal;
            }
        }

  Answered by     Sathya Narayanan, Software Developer Aricent Technologies  | 03 04 2009 16:53:51 +0000
[ Delete ]
[ Edit ]
Rating : +1 

Hi all these are one method and you can use SQLHelper which is a standard helper file provided by microsoft

and which will be very much useful for using it in the Data logic layer of all ur .net applications.

code will be like this :

include this sqlhelper.cs : http://www.koders.com/csharp/fidD4121D6E4BCA2DAB656D770903FECBFF7427D242.aspx?s=mdef%3Ainsert

to your solution :

 

using Helper.SQLHelper;

SqlParameter[] Param = new SqlParameter[2];           
            Param[0] = new SqlParameter("@number", objBLL.nNo);                                   
            Param[1] = new SqlParameter("@name", objBLL.strname);

            DataSet dsstudentdetails = new DataSet();
            dsstudentdetails = SqlHelper.ExecuteDataset(strSQLConnectionString, CommandType.StoredProcedure, "Getstudentdetails", Param);
           

            if (dsstudentdetails.Tables.Count > 0)
            {
                return dsstudentdetails;
            }
            else
            {
                return dsstudentdetails;
            }

 

here objbll is the  business logic layer object for which u can pass data from ur presentation layer and the total bll is passed to the function

  Answered by     Darpan Sinha, Tech Architect, Royal Bank of Scotland  | 02 15 2009 06:51:06 +0000
[ Delete ]
[ Edit ]
Rating : +1 

Just making it more appropriate

SqlConnection theCon;
           
            theCon = "<your Connection>";
            SqlCommand theCommand;
            theCommand = new SqlCommand("PR_MMS_ISSUESUMMARY_MAX", theCon);
           
            theCommand.CommandType = CommandType.StoredProcedure;
            theCommand.CommandTimeout = 180 //in secs
            theCommand.Parameters.Add("@fromdate", SqlDbType.DateTime);
            theCommand.Parameters["@fromdate"].Value = fromdate.Value.ToString("yyyy-MM-dd") ;
            theCommand.Parameters.Add("@todate",SqlDbType.DateTime);
            theCommand.Parameters["@todate"].Value = todate.Value.ToString("yyyy-MM-dd") ;
            theCommand.Parameters.Add("@loggedstationid", SqlDbType.Int);
            theCommand.Parameters["@id"].Value = id
            theDs=new DataSet();
            SqlDataAdapter theAdapater = new SqlDataAdapter(theCommand);

try

{
            theAdapater.Fill(theDs);
            return theDs;

}

catch(SqlException ex){

//Do what u like;

}

finally{

theCon.Close();

theCon.Dispose();

theCommand.Dispose();

}

  Answered by     Abhishek Shrivastava, Software Developer, value-one Infotech  | 02 02 2009 12:45:49 +0000
[ Delete ]
[ Edit ]
Rating : +1 

 SqlConnection theCon;
           
            theCon = "<your Connection>";
            SqlCommand theCommand;
            theCommand = new SqlCommand("PR_MMS_ISSUESUMMARY_MAX", theCon);
           
            theCommand.CommandType = CommandType.StoredProcedure;
            theCommand.CommandTimeout = 180 //in secs
            theCommand.Parameters.Add("@fromdate", SqlDbType.DateTime);
            theCommand.Parameters["@fromdate"].Value = fromdate.Value.ToString("yyyy-MM-dd") ;
            theCommand.Parameters.Add("@todate",SqlDbType.DateTime);
            theCommand.Parameters["@todate"].Value = todate.Value.ToString("yyyy-MM-dd") ;
            theCommand.Parameters.Add("@loggedstationid", SqlDbType.Int);
            theCommand.Parameters["@id"].Value = id
            theDs=new DataSet();
            SqlDataAdapter theAdapater = new SqlDataAdapter(theCommand);
            theAdapater.Fill(theDs);
            return theDs;

 
 
Viewers also viewed
Dynamic Management Views   The dynamic management views (DMV’s) in SQL Server 2005 are designed...
 
11 referals 6 comments, 1828 views
Whichever sort of communication it is whether its in organizations or whether its from a product...
 
1360 referals 68 arguments, 764 views
AS BOTH VLSI EMBEDDED ARE CHIP DESIGN LEVEL PROGRAMMING WHICH ONE IS BETTER? MEANS WHICH HAVING...
 
1 referals 9 arguments, 5168 views
more...  
Unanswered Questions (17)
 
0 referals 0 answers, 0 views
When there is already existing your brand name with well known products, how to come up with few...
 
503 referals 1 answers, 58 views
To brief on myself, I am P2P, PMP, MBA(IT), B.E.(CS), Oracle SCWCD, J2EE Professional with 8+...
 
0 referals 0 answers, 0 views
More From Author
Hi friends, I'm new to Visual C++. And I want to know the real world applications which are developed by using VC++. If you know the answer, please post your answer here or http:\\computerprogramminghelp.blogspot.com
How to change the image size when hover the mouse?
How to call a stored procedure using SQL Server 2000 and C#.NET?
more...