0

I am working on a website which is developed in ASP.NET and backbend is C#. I am dynamically trying to pass the value from the Database to the header. I can do this for the user name by simply doing <%: Context.User.Identity.GetUserName() %> and that will return the correct user name. How would I do this for a course name?

Below is my code which reads the values from the DB

public DataTable GetCourseData()
{
    string UsrName = User.Identity.Name;
    DataSet dt = new DataSet();

    using (SqlConnection connection = new SqlConnection(Common.ConnectionString))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT CourseName FROM Course WHERE UserName=@UserName"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                SqlParameter para2 = new SqlParameter("UserName", UsrName);
                cmd.Parameters.Add(para2);
                cmd.Connection = connection;
                sda.SelectCommand = cmd;
                sda.Fill(dt);
            }
        }
    }
    return dt.Tables[0];
}

If I do <%: GetCourseData() %> it doesn't return the course.

Any help would be much appreciated!

6
  • What is the Question? GetCourseData returns a DataTable. That ToString likely returns some nice text - namely "DataTable" unless I am mistaken (type is the default ToString). Antipatterns again - try making this an object and then grab the right field. Commented Nov 11, 2014 at 11:30
  • I want to get the course name and display it on the page Commented Nov 11, 2014 at 11:32
  • You want a string instead of the DataTable? Commented Nov 11, 2014 at 11:33
  • @mot Yes, that's exactly what I am after Commented Nov 11, 2014 at 11:34
  • So the question is: Is there anyone that can code this piece for me? Commented Nov 11, 2014 at 11:34

1 Answer 1

1

The problem you have is you return a DataTable which describes a whole table with your query results. You probably want to get the data you need from it, like so:

return dt.Tables[0].Rows[0]["CourseName"];
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer! I have completely changed my method to return a string and got it to work. However your solution is also helpful so I will accept it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.