Solved

Connect to MSSQL db using C#

Posted on 2007-12-06
7
12,034 Views
Last Modified: 2013-11-26
Using Visual Web Developer 2005 (C#) to create an ASP 2.0 web form.

I've created a data grid on the page that displays the rows of a table and as a result it has created a connection string to my MSSQL2000 db in web.config.

I want to be able to create my own functions in the .aspx.cs file with their own SQL statements (for UPDATE/INSERT, etc) but I don't know how to reference the connection string in web.config to do that. Can someone help?

If you need me to be more specific, I'll try my best. I'm pretty new to .NET.
0
Comment
Question by:victornegri
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
7 Comments
 
LVL 22

Expert Comment

by:RedKelvin
ID: 20424548
Hi

Hopefully you will find this useful
http://msdn2.microsoft.com/en-us/library/ms998292.aspx


<connectionStrings>
  <add name="MyDbConn1" 
       connectionString="Server=MyServer;Database=MyDb;Trusted_Connection=Yes;"/>
  <add name="MyDbConn2" 
      connectionString="Initial Catalog=MyDb;Data Source=MyServer;Integrated Security=SSPI;"/>
</connectionStrings> 

Open in new window

0
 
LVL 10

Author Comment

by:victornegri
ID: 20424937
Unfortunately I can't use Windows Authentication to connect to the SQL server.

... and I already have the connection strings in my web.config file. I'm wondering how I can reference them in my .aspx.cs file so I can create functions that can do Update/Insert/Select queries on specific tables.
0
 
LVL 22

Expert Comment

by:RedKelvin
ID: 20425241
0
Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

 
LVL 10

Expert Comment

by:digitalZo
ID: 20425607
You can reference it as:
string connStr = ConfigurationManager.ConnectionStrings("[connectionstringname]").ConnectionString;
 
sqconn = New SqlConnection(connStr);

Open in new window

0
 
LVL 12

Accepted Solution

by:
needo_jee earned 500 total points
ID: 20426068
Here is the way to do that....
//IN WEB.CONFIG ADD FOLLOWING
<connectionStrings>
  <add name="MyConnectionString"  connectionString="Data Source=PCSQL2K;Initial Catalog=Northwind;Integrated Security=True"
   providerName="System.Data.SqlClient";"/>
 </ConnectionString>
 
 
//In ASP.NET FORM LOAD EVENT create connection with this connectionsrting
add name spaces
using System.Data.SqlClient;
using System.Configuration;
 
public partial class ASPtoASPX : System.Web.UI.Page
{
    SqlConnection sCon;
    SqlCommand sCom;
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            sCon = new SqlConnection(ConfigurationManager.AppSettings.Get("MyConnectionString"));
            sCom = new SqlCommand(); // or sCom = new SqlCommand("Select * from products",sCon);
            sCom.Connection = sCon;
            sCom.CommandText = "insert into test table(ID,Name) values('testID','TestName'";
            sCon.Open();
            sCom.ExecuteNonQuery(); // to insert use nonquery and to fetch you may use execute scaler or reader 
            
            sCom.Dispose(); 
            sCon.Dispose(); 
        }
    }
}

Open in new window

0
 
LVL 10

Author Comment

by:victornegri
ID: 20428261
Thanks. I'll try that!
0
 
LVL 10

Author Comment

by:victornegri
ID: 20434644
OK. Got it working... somehow. My main problem was that I didn't have the using System.Data.SqlClient; statement.

Had to use the following connection string:
public SqlConnection sCon = new SqlConnection(ConfigurationSettings.AppSettings.GetValues(0).GetValue(0).ToString());
Does anyone see anything wrong with this statement? I put it outside of the function so that I could use it in different functions.

When I used the connection strings supplied above, they didnt' work. I got different errors. (i.e. "The ConnectionString property has not been initialized." or something about using a property as a method).

The rest of my code is as follows. Please comment on my approach and let me know if I'm doing something stupid:

SqlCommand cmd_Fill_pnlList = new SqlCommand();
 
            cmd_Fill_pnlList.Connection = sCon;
            cmd_Fill_pnlList.CommandText = String.Format("SELECT * FROM tblParts WHERE PartNo = '{0}'",lblPartNoHidden.Text);
 
            SqlDataAdapter adp_Fill_pnlList = new SqlDataAdapter();
            adp_Fill_pnlList.SelectCommand = cmd_Fill_pnlList;
 
            DataSet ds_Fill_pnlList = new DataSet();
            adp_Fill_pnlList.Fill(ds_Fill_pnlList, "tblFill_pnlList");

Open in new window

0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question