Tuesday, March 16, 2010

C#/ASP Beginners Notes

Someone asked me yesterday about some beginners stuff, so I thought I would post the questions:
1.  How do I find the current users name on my website?  Pretty easy, use Page.User.Identity.Name.

2.  How do I get data from a database?  Well, this is pretty simple too.  First I would tell you to drop a SqlDataSource Object onto any of your pages and go through the wizard to configure it to connect to the database your wanting to pull information out of.  When it asks you if you want to store it in the web config say yes and take not of the key name you use when you store it.  The table or select statement you choose during the wizard doesn’t really matter.  You can even delete the object after you complete the wizard the point is to get the webconfig entry created.  Now, go look at your web config and see the connectionstrings section?  That is the database connection you just setup.  If you feel comfortable with it you can just create your entries just like this one in the web config for any database connections.  Just remember the name because we are gonna need that next.  Anyways your web config should now have something like this:

    <connectionStrings>
        <add name="myConnection" connectionString="Data Source=MySqlServer;Initial Catalog=MyDatabase;Integrated Security=True" providerName="System.Data.SqlClient"/>

    </connectionStrings>

Now we can get some data by doing this:

Protected void GetMyData()
{
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter();
            SqlConnection cnConn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnections"].ConnectionString);

            da.SelectCommand = new SqlCommand("SELECT * FROM myTable", cnConn);
            try
            {
                cnConn.Open();
                da.Fill(dt);
                cnConn.Close();
                cnConn.Dispose();

            }
            catch (Exception ex)
            {
                cnConn.Close();
                cnConn.Dispose();
            }
}

Inside the try block you will want to do whatever you want with the data in dt.  For example if you are using a DataGrid to display this data then you could add:

Datagrid.Datasource = dt;
Datagrid.Databind();

Into the try block to populate the grid with the data.

No comments: