Duddupudi Bhargav Duddupudi Bhargav - 1 month ago 12
C# Question

whats the use of data adapter

Can anyone explain why an

SqlDataAdapter
is used in the following code? The code is working fine without this adapter.

Also, why do we use
DataAdapter
? Please help me to understand this
DataAdapter
usage.

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Data Source=.....\\SQLEXPRESS;Initial Catalog=......;Integrated Security=True");
con.Open();

SqlDataAdapter da =new SqlDataAdapter(); // Why use `SqlDataAdapter` here?
SqlCommand sc = new SqlCommand("insert into bhargavc values(" + textBox1.Text + "," + textBox2.Text + ");", con);
var o = sc.ExecuteNonQuery();
MessageBox.Show(o + "record to be inserted");
con.Close();
}
catch (Exception)
{
MessageBox.Show("error in the code");
}
}

private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}

private void Form1_Load(object sender, EventArgs e)
{
}
}
}

Answer Source

There are several reasons to use a DataAdapter:

  1. You can't fill a DataSet without one.
  2. When the adapter completes its .Fill() method, it will close the connection for you; you don't have to explicitly call the .Close() method on your connection object. Although, it is still good practice to.

In your case, it isn't necessary to have one though. But, if you did want to use one, the implementation would look like this:

SqlDataAdapter da = new SqlDataAdapter();     
DataSet ds = new DataSet();
da.Fill(ds);

From there, there are further actions that you can take on the ds object like exporting to Excel via Interop, filling a DataGridView or even updating a database table.