views:

40

answers:

1

I'm developing a website in that, i couldn't create connection string ,i have included all the required namespaces but when i create a string variable to store the connection it wont come in declaring SqlConnection object, but i can able to create connection string in constructor class,why i can't able to create connection outside constructor. is there any specific reason..

A: 

App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="main" providerName="System.Data.SqlClient" connectionString="Data     Source=localhost;Initial Catalog=mydatabase;User Id=myid;Password=mypassword;"/>
  </connectionStrings>
<configuration>

C# code:

using System.Configuration;

public string _connectionString = ConfigurationManager.ConnectionStrings[1].ConnectionString;

public string GetString(string sql, SqlParameter[] parameters)
{
  List<string> result = new List<string>();
  SqlDataReader reader;
  using (SqlConnection connection = new SqlConnection(_connectionString ))
  {
    SqlCommand command = new SqlCommand(sql, connection);
    if (parameters != null)
    {
      command.Parameters.Clear();
      command.Parameters.AddRange(parameters);
    }
    connection.Open();
    reader = command.ExecuteReader();
    while (reader.Read())
    {
      string row = string.Empty;
      foreach (string col in reader)
      {
        row += col + ",";
      }
      result.Add(row)
    }
    reader.Close();
  }
  return result;
}
JohnB
thanks a lot, guys i'm new to this C# thats y struggle to express it
chandru
@candru: Does this answer help you with your question at all?
JohnB