Pages

Thursday, February 4, 2010

Return Dataset or Datatable With SqlDataAdapter C# .Net

using System.Data.SqlClient;

 SqlDataAdapter class used with Select Query to return Dataset/DataTabel as needed
e.g.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace BindCombo
{
public partial class Form1 : Form
{
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter da;
SqlTransaction st;
bool error;
public Form1()
{
InitializeComponent();
  con = new SqlConnection("Data Source=Node1;Initial Catalog=ERP;Persist Security Info=True;User ID=12345;Pooling=False;Password=adc");
   cmd = new SqlCommand("Select AreaID,AreaCode from Area", con);
try
{
DataSet ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);

cmbList.DataSource = ds.Tables[0];
cmbList.DisplayMember = "AreaCode";
cmbList.ValueMember = "AreaID";
}
catch
{
error = true;
}
finally
{
//if (error == true) { st.Rollback(); }
//else { st.Commit(); }
}
}

private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(Convert.ToString((int)cmbList.SelectedValue));
}
}
}