2

I am currently studying as web developer, and are learning ASP.NET WEBFORMS. I have a question regarding DataAdapter and Updating/Deleting a table.

I wanna know which is the right way to do this. Lets say I have this method.

The Update Method

public void UpdateDataTable()
    {
        SqlConnection conn = new SqlConnection(strcon);
        SqlDataAdapter da = null;
        DataSet ds = null;
        DataTable dt = null;
        string sqlsel = "SELECT ActId, Title FROM Act WHERE ArtistId = " + Session["UserId"];

        try
        {
            da = new SqlDataAdapter();
            da.SelectCommand = new SqlCommand(sqlsel, conn);

            ds = new DataSet();
            da.Fill(ds, "MyTable");

            dt = ds.Tables["MyTable"];

            Gridview1.DataSource = dt;
            Gridview1.DataBind();
        }
        catch (Exception ex)
        {
            LabelMessage.Text = ex.Message;
        }
        finally
        {
            conn.Close();              
        } 
    }

I call this method at when the pages load in a (!Page.IsPostBack). So my question is, since a DataSet saves it all in memory (DataTable too). And I want to Update one row with the DataAdapter object again, which method is the best to use? In a click event.

Method 1

protected void ButtonUpdate_Click1(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(strcon);
        SqlDataAdapter da = null;
        string sqlupd = "UPDATE [Act] SET [Title] = @Title, [Description] = @Description, [Duration] = @Duration WHERE [ActId] = @ActId";

        try
        {

            conn.Open();
            da = new SqlDataAdapter();

            da.UpdateCommand = new SqlCommand(sqlupd, conn);

            da.UpdateCommand.Parameters.AddWithValue("@Title", TextBoxTitle.Text);
            da.UpdateCommand.Parameters.AddWithValue("@Description", TextBoxText.Text);
            da.UpdateCommand.Parameters.AddWithValue("@Duration", TextBoxDuration.Text);
            da.UpdateCommand.Parameters.AddWithValue("@ActId", LabelID.Text);

            da.UpdateCommand.ExecuteNonQuery();

        }
        catch (Exception ex)
        {
            LabelMessage.Text = "" + ex.Message;
        }
        finally
        {
            conn.Close();
        }
        // Call the Update Method
        UpdateDataTable();
}

Or is it better to populate all again, and put it in the DataSet -> DataTable? Like this.

Method 2

protected void ButtonUpdate_Click1(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection(strcon);
            SqlDataAdapter da = null;
            DataSet ds = null;
            DataTable dt = null;
            SqlCommand cmd = null;
            string sqlsel = "SELECT  * FROM Act WHERE ArtistId = " + Session["UserId"];
            string sqlupd = "UPDATE [Act] SET [Title] = @Title, [Description] = @Description, [Duration] = @Duration WHERE [ActId] = @ActId";

            try
            {   

                da = new SqlDataAdapter();


                da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand(sqlsel, conn);

                ds = new DataSet();
                da.Fill(ds, "MyTable");

                dt = ds.Tables["MyTable"];

                dt.Rows[Gridview1.SelectedIndex]["Title"] = TextBoxTitle.Text;
                dt.Rows[Gridview1.SelectedIndex]["Description"] = TextBoxText.Text;
                dt.Rows[Gridview1.SelectedIndex]["Duration"] = TextBoxDuration.Text;


                // UPDATE
                cmd = new SqlCommand(sqlupd, conn);
                cmd.Parameters.Add("@Title", SqlDbType.NVarChar, 50, "Title");
                cmd.Parameters.Add("@Description", SqlDbType.Text, 250, "Description");
                cmd.Parameters.Add("@Duration", SqlDbType.Int, 4, "Duration");

                SqlParameter parm = cmd.Parameters.Add("@ActId", SqlDbType.Int, 4, "ActId");
                parm.SourceVersion = DataRowVersion.Original;

                da.UpdateCommand = cmd;
                da.Update(ds, "MyAct"); 

            }
            catch (Exception ex)
            {
                LabelMessage.Text = "" + ex.Message;
            }
            finally
            {
                conn.Close();
            }
            UpdateDataTable();
;
        }

So which method is the best to use? And why? :)

Sigils
  • 2,492
  • 8
  • 24
  • 36
  • 1
    Why web forms?! Anyway your data should come form a service, that is you don't access the db from the UI, page behind. And this means that data sets & co.are not your best choice of doing things. If you are learning , at least try to learn the good practices from the beginning, it's much harder to change your habits later – MikeSW Jan 19 '14 at 10:47
  • Thanks for the answer MikeSW! Well why webforms? I asked myself the same question, but it is a part of the study curriculum. So we are forced to learn it, after this semester I will take a look at .NET MVC :) But this is actually from a school project (already delivered) and one of the goals was that you should use DataAdapter, I know that in this case that a DataReader to read the table and a simple Command with ExecuteNonQuery could have worked better since I am only working with one table. – Sigils Jan 19 '14 at 11:42
  • If it's for school, don't worry, hopefully you won't be needing this in the real world. – MikeSW Jan 19 '14 at 11:45
  • If there's only one table then why use a DataSet? DataAdapter can Fill a DataTable directly. – StevieB Jan 19 '14 at 11:48
  • @MikeSW I am glad you say that, hopefully you are right! – Sigils Jan 19 '14 at 11:55
  • @StevieB , you mean I should just use the DataAdapter Fill method and instantly go to the DataTable? – Sigils Jan 19 '14 at 11:56
  • You can also use SqlCommandBuilder to automatically create your update, delete and create commands e.g. SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da); // da being the DataAdapter. Note: Do this after setting the da.SelectCommand. Then the update handler merely needs to call da.Update(dt); // dt being the DataTable. – StevieB Jan 19 '14 at 11:59
  • @Sigils yup. DataTable dt; .... adapter.Update(dt); – StevieB Jan 19 '14 at 12:00
  • @StevieB Thanks a lot for the tips. Didn't knew about the SqlCommandBuilder! – Sigils Jan 19 '14 at 12:05

1 Answers1

0

Neither is a good choice, placing any DAL code in your code-behind/controller/view is a BIG no no and is a very short sighted coding practice. You should have some basic Model, BusinessLogic and DAL namespace classes to work with.

T McKeown
  • 12,971
  • 1
  • 25
  • 32
  • Thanks pal, didn't knew that. But unfortunately, that is how they taught us in my school :/. But I am glad you are telling me how things REALLY should be! – Sigils Jan 20 '14 at 09:10