?
Solved

Bind a Datagrid to an SQL Server table

Posted on 2004-08-18
4
Medium Priority
?
222 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 1000 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 1000 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

Industry Leaders: 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

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
Suggested Courses
Course of the Month10 days, 4 hours left to enroll

762 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