Solved

Bind a Datagrid to an SQL Server table

Posted on 2004-08-18
4
219 Views
Last Modified: 2010-04-15
Hi,

   I have a table called country in the SQL Server database called DEV.

   I want to bind "Select * from country" to a DataGrid called DG_COUNTRY.

   Please give me the C# code to do that.



Thanks



Robert
0
Comment
Question by:rogaut1
[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
4 Comments
 
LVL 9

Accepted Solution

by:
s_sansanwal earned 250 total points
ID: 11837453
You should try to this by yourself rather asking for full question as this would help you to learn.

Anyway, the solution to your question is

private void Form1_Load(object sender, System.EventArgs e)
            {
                  System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection("Initial Catalog=DEV;Data Source=localhost;Integrated Security=SSPI;");
                  System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter();
                  try
                  {
                        //connection.Open();
                        string sql = "SELECT * FROM country";
                        System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand();
                        command.CommandText = sql;
                        command.Connection = connection;
                        adapter.SelectCommand = command;
                        DataSet ds = new DataSet();
                        adapter.Fill(ds);
                        this.DG_COUNTRY.DataSource  = ds.Tables[0];
                  }
                  catch(Exception exp)
                  {
                        
                        MessageBox.Show(String.Format("An exception occurred : {0}. Please contact your system administrator.", exp.Message));
                  }
                  
                  }


Cheers,
S Sansanwal
0
 
LVL 3

Assisted Solution

by:nhewitt21
nhewitt21 earned 250 total points
ID: 11839311
is this for the web or for a windows form?

Here's my connections string that i put in the web.config (replace xxx with your details):
<appSettings>
      <add key="SQLDBConnectionString" value="server=xxx;database=xxx;uid=xxx;pwd=xxx;" />
</appSettings>

Here a web solution to get the data and put it into a dataset:
public static System.Data.DataSet Populate_Country()
{
      DataSet ds = new DataSet();
      SqlConnection oCn = new SqlConnection(ConfigurationSettings.AppSettings["SQLDBConnectionString"]);
      SqlCommand oCm = new SqlCommand("sp_Country#Select_All", oCn);
      oCm.CommandType = CommandType.StoredProcedure;

      SqlDataAdapter da = new SqlDataAdapter();
      da.SelectCommand = oCm;  
      da.Fill(ds);

      try
      {
            oCn.Open();
            oCm.ExecuteNonQuery() ;
      }
      catch (Exception ex)
      {
            ds.Tables.Add(ex.ToString());
      }      
      finally
      {
            oCm.Dispose();
            oCn.Dispose();
      }

      return ds;
}

Code to call the above function and bind to dataset:
DataSet ds = YourProject.location_of_file_containing_function.Populate_Country();

DG_COUNTRY.DataSource = ds;
DG_COUNTRY.DataBind();

Your stored procedure code:
CREATE PROCEDURE sp_Country#Select_All

AS
BEGIN TRAN
      SELECT * FROM Country

IF (@@error = 0)
BEGIN
      COMMIT TRANSACTION
      RETURN(0)
END
ELSE
BEGIN
      GOTO ErrorHandler
END
ErrorHandler:
ROLLBACK TRANSACTION
RETURN (1)
GO

I would use a stored procedure over inline sql code, its more secure.

if you want to implement sorting to your columns check this out:
http://www.experts-exchange.com/Programming/Programming_Languages/C_Sharp/Q_21082798.html
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

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

733 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