niceoneishere
niceoneishere

Reputation: 343

Save data to SQL DB using a class in C#

Sorry If I am posting this question in the wrong forum. This is my first time posting at Stackoverflow. And Also I am learning ASP.NET and C# by myself so pardon me if this elementary.

I have created a class file in ASP.NET 4.0 C# using visual studio 2010. My code is like below

namespace My.Customers
{
    public class EmailMailingList
    {
        #region members

        private string _emailList;

        #endregion

        #region properties

        /// <summary>
        /// gets or sets Customer Email for Mailing List
        /// </summary>
        public string EmailList
        {
            get { return _emailList; }
            set { _emailList = value; }
        }

        #endregion
    }
}

I have a Database table in SQL 2008 named MailingList with 2 fields namely Id and Email where Id is int with auto increment and Email Varchar(50).

I also created a Stored Procedure based on this table to enter the email address.

where I am getting confused is How can I add this info to my class file so the data can be saved to the database.

I also created a web form called Join-Mailing-List.aspx with a textbox called tbEmail and a Submit Button called Join.

What I am trying to is when someone enters the email address in the textbox I want to pass the textbox value to string EmailList in my class file and save the data to the database.

I know how to pass the textbox value to my class file. I just dont know how to save the info to the DB without using the DB code in the aspx page

Thanks and really appreciate for any advice or examples

Upvotes: 3

Views: 12406

Answers (4)

codingbiz
codingbiz

Reputation: 26376

There are several ways you can approach saving into database

Here is one: (simpler in my opinion)

public class EmailMailingList
{

    private string _emailList;

    public string EmailList
    {
        get { return _emailList; }
        set { _emailList = value; }
    }

    #endregion

   public void Save()
   {
      //Insert (this.EmailList); to database
   }
}

//Use:
EmailMailingList ml = new EmailMailingList();
ml.EmailList = "blah";
ml.Save();

Some school of thought frown at that.

Another is creating a special class to do that

public class MailingListSaver
{
   public static void Save(EmailMailingList ml)
   {
      //insert (ml.EmailList) into database
   }
}

//Use:
EmailMailingList ml = new EmailMailingList();
ml.EmailList = "blah";
MailingListSaver.Save(ml);

Look into (google)

  • Active Record Pattern
  • Repository Pattern
  • N-tier application c#

Upvotes: 1

Edward Pescetto
Edward Pescetto

Reputation: 926

I would recommend using the entity data model. It is the quickest, easiest way and it is a "best practice." You should get started bu walking through this tutorial:

http://www.asp.net/web-forms/tutorials/getting-started-with-ef/the-entity-framework-and-aspnet-getting-started-part-1

Once you have your datamodel set up using the wizard, then it is really quick and simple to save your data from a form on the code side:

dataModel.dataEntities de;
dataModel.dataTable tbl;

protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSubmit_Click(object sender, EventArgs e)
{
    //Create new entity object and table object
    de = new dataModel.dataEntities();
    de.Connection.Open();

    tbl = new dataModel.DataEntities();

    tbl.Field1 = ((TextBox)tbField1).Text.ToString(); ;
    tbl.Field2 = ((TextBox)tbField2).Text.ToString(); ;

    //Insert the row and save the change to the table
    de.AddToDataTable(tbl);
    de.SaveChanges();

    de.Connection.Close();
}

Upvotes: 0

Abe Miessler
Abe Miessler

Reputation: 85036

There are a number of different ways to save information to a database using C#. Some of the more common:

You will probably need to read up on those to find the best one for you. If you want something quick and relatively easy, I would probably go with ADO.NET but others may disagree.

As far as how to include the code for the update in your class you could just add an Update() or Save() function.

Upvotes: 3

Didaxis
Didaxis

Reputation: 8736

You can simplify your class a little for clarity:

public class EmailMailingList
{
    public string EmailList { get; set; }
}

Then you have MANY options for getting this info to your db. If you're just starting out, I think plain ol' ADO.Net is a get choice for getting accustomed to things. Something like:

// A method in your code-behind:
public void Save(EmailMailingList list)
{
    using(var connection = new SqlConnection("your connection string"))
    {
        var command = connection.CreateCommand();
        command.CommandText = "name of your stored procedure";
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add(new SqlParameter( ... ));
        command.ExecuteNonQuery();
    }
}

Of course, eventually you'll want to look into the powerful ORMs available to you in the .Net world (Entity Framework, NHibernate, LinqToSql)

Upvotes: 0

Related Questions