Nice C# class for ADO.net databinding

Nice class with a couple of methods to handle execution of a stored procedure with an array of parameters or a regular query and return a dataset object, all you need do is pass in the connection string when creating the connection.

[codesyntax lang="csharp"]
using System;
using System.Data.SqlClient;
using System.Data;

namespace Connection
{
  public class Connect
  {
    private SqlConnection sqlConn;

    // Constructor
    public Connect(string ConnectionString)
    {
      sqlConn = new SqlConnection(ConnectionString);
    }

    // Open the connection 
    public void OpenCon()
    {
      sqlConn.Open();
    }

    // Close the connection 
    public void CloseCon()
    {
      sqlConn.Close();
    }

    public DataSet ExecuteProc(string spName, SqlParameter[] spParams)
    {
      try
      {
        SqlCommand cmd = new SqlCommand(spName, sqlConn);
        cmd.CommandTimeout = 0;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Clear();
        if (spParams != null)
        {
          cmd.Parameters.AddRange(spParams);
        }
        DataSet ds = new DataSet();
        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
        {
          OpenCon();
          da.Fill(ds);
          cmd.Dispose();
          da.Dispose();
        }
        return ds;
      }
      catch (Exception ex)
      {
        throw new Exception("Error while executing the stored proc : " + ex.Message);
      }
      finally
      {
        CloseCon();
      }
    }

    public DataSet ExecuteQuery(string queryString)
    {
      try
      {
        SqlCommand cmd = new SqlCommand(queryString, sqlConn);
        cmd.CommandTimeout = 0;
        cmd.CommandType = CommandType.Text;

        DataSet ds = new DataSet();
        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
        {
          OpenCon();
          da.Fill(ds);
          cmd.Dispose();
          da.Dispose();
        }
        return ds;
      }
      catch (Exception ex)
      {
        throw new Exception("Error while executing the query : " + ex.Message);
      }
      finally
      {
        CloseCon();
      }
    }

  }
}
[/codesyntax]

 

Usage in your code behind, place these using directives

[codesyntax lang="csharp"]
using Connection;
using System.Data.SqlClient;
[/codesyntax]

Call a stored procedure in an event within the page such as follows

[codesyntax lang="csharp"]
Connect Conn = new Connect(WebConfigurationManager.ConnectionStrings["NAMEOFCONNECTIONSTRING"].ConnectionString);
      Conn.ExecuteProc("AddRecord", new SqlParameter[] {
      new SqlParameter("@Name", txtName.Text),
      new SqlParameter("@Address", txtAddress.Text),
      new SqlParameter("@Telephone", txtTelephone.Text),
      new SqlParameter("@Comments", txtComments.Text),
      new SqlParameter("@CodeField", ddlCodeField.SelectedValue),
    });
[/codesyntax]

Set parameter value of SqlDataSource to SelectedValue of another page control

You have a DetailsView control with edit / add and all the other goodness enabled, but when adding a new record you want a non-visible field to get it’s value from another control like the SelectedValue of a GridView or a DropDownList in the InsertParameters collection of your SqlDataSource just use a ControlParameter instead

[codesyntax lang="csharp"]
<InsertParameters>
    <asp:ControlParameter ControlID="ddlYourList" Name="ParameterName"
        PropertyName="SelectedValue" Type="Int32" />
    <asp:Parameter Name="SomeDetailsViewParameter" Type="String" />
</InsertParameters>
[/codesyntax]

Bind a Dataset to a Listbox using OleDbDataAdapter

Need to bind a web control to an OleDb data source in your C# web application, here’s the magic. In this case I am binding a ListBox control with an ID of ListBox1 to the ProductName field in the Products table of our old friend the Northwind database.

These are the using statements that you need to apply including the ConfigurationManager to get your web.config connection string conveniently

[codesyntax lang="csharp"]
using System.Data;
using System.Data.OleDb;
using System.Configuration;
[/codesyntax]

Here is our class that does all the work

[codesyntax lang="csharp"]
protected void DataSetFromOleDbDemo()
    {
      string strSQL = "SELECT * FROM Products WHERE CategoryID = 1";

      var conString = ConfigurationManager.ConnectionStrings["Northwind"];
      string Conn = conString.ConnectionString;

      try
      {
        using (OleDbDataAdapter adapter = new OleDbDataAdapter(strSQL, Conn))
        {
          DataSet ds = new DataSet();
          adapter.Fill(ds, "ProductInfo");

          foreach (DataRow dr in ds.Tables["ProductInfo"].Rows)
          {
            ListBox1.Items.Add(dr["ProductName"].ToString());
          }
        }
      }
      catch (Exception)
      {

        throw;
      }
    }
[/codesyntax]

And your OleDb connection string to put in the connectionStrings section of your web.config is as follows

[codesyntax lang="xml"]
<connectionStrings>
    <add name="Northwind" connectionString="Provider=SQLOLEDB;server=YOURSERVER;database=Northwind;uid=USERNAME;password=PASSWORD;" />
</connectionStrings>
[/codesyntax]

 

 

Populate a DropDownList with the names of installed fonts with C#

Need to get a list of available fonts for your application?, this little gem will retrieve the font names of all installed fonts on your server (asp.net) and use them to populate a DropDownList.

These are the namesspaces you need to import to get this running.

[codesyntax lang="csharp"]
using System.Drawing;
using System.Drawing.Text;
[/codesyntax]

Assuming your DropDownList has an ID of “ddl”

[codesyntax lang="csharp"]
<asp:DropDownList ID="ddl" runat="server" />
[/codesyntax]

Your codebehind just needs an installed font collection object created with a foreach loop to go through in your Page_Load event.

[codesyntax lang="csharp"]
      InstalledFontCollection fonts = new InstalledFontCollection();

      foreach (FontFamily family in fonts.Families)
      {
         ddl.Items.Add(family.Name);
      }
[/codesyntax]

Binding a GridView in C# with a parameterized command

With two controls on your asp.net page a DropDownList (ID ddlDropDownList) and a GridView (ID gvGridView), to retrieve the SelectedValue from the DropDownList and use that in the where clause of the query used to bind data to your GridView the following will help.

Required using statements

[codesyntax lang="csharp"] using System.Data;
using System.Data.SqlClient;
using System.Configuration;
[/codesyntax]

ADO.NET block of code to base your bind on using an SQLDataAdapter so you can still have paging on the GridView.

[codesyntax lang="csharp"]
    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["CONNSTRINGNAME"].ConnectionString))
    {
      using (SqlCommand cmdGrid = new SqlCommand("SELECT * FROM TABLE WHERE FIELD = @PARAMETER", con))
      { 
      cmdGrid.Parameters.AddWithValue("@PARAMETER", ddlDropDownList.SelectedValue);
      con.Open();

      using (SqlDataAdapter da = new SqlDataAdapter(cmdGrid))
      {
        DataTable dt = new DataTable();
        da.Fill(dt);           
        gvGridView.DataSource = dt;
        gvGridView.DataBind();
      }
      }
    }
[/codesyntax]

The structure of the code is with using statments to ensure the garbage collection is carried out efficiently.