Results 1 to 9 of 9

Thread: [RESOLVED] Getting SQL data into Label not DataGrid

  1. #1

    Thread Starter
    Fanatic Member invitro's Avatar
    Join Date
    Jan 2000
    Location
    Outside your window
    Posts
    547

    Resolved [RESOLVED] Getting SQL data into Label not DataGrid

    I do not understand why every tutorial website that I go to uses the DataGrid control as an example.

    Is this standard, should I also be using this control in my project?

    I have a page called Article.aspx. It displays one image and one article that is pulled from a database.

    I want to display this data using: <asp:Image src="image link"> and <asp:label text="body of the article"> not as a <asp:datagrid>

    I have no problem with the DataGrid control, it just seems like overkill since I only need 1 row from the database. I also do not want this information in a grid, I would like to have the power to place it wherever I desired. I.E, I want to put the article image on the left, article title on the top, and the body of the article in the middle of the page... you get the idea.

    Is there something I am missing here? Could one not do something like:

    Code:
        LabelArticleBody.Text = ds.Tables["tblArticle"].Columns[1].???;

    Incase you are interested, this is what my pageload looks like:

    Code:
    protected void Page_Load(Object sender, EventArgs e)
    {
        String strCategoryID;
        String strArticleID;
    
        strCategoryID = Request.QueryString["sci"];
        strArticleID = Request.QueryString["sai"];
        
    	SqlConnection sqlCon = new SqlConnection("private");
    	SqlDataAdapter myCommand = new SqlDataAdapter("SELECT * FROM tblArticle WHERE tblArticle.charArticleID='" + strArticleID + "' AND tblArticle.charCategoryID='" + strCategoryID + "'",sqlCon);
    	
    	DataSet ds = new DataSet();
    	myCommand.Fill(ds, "tblArticle");
    	
    	/* gridArticle.DataSource=ds.Tables["tblArticle"].DefaultView;
    	    gridArticle.DataBind();
                Great for testing but I do not want to use a DataGrid.  
            */
        
        //lblArticleBody.Text = ds.Tables["tblArticle"].???;  -- whats the missing piece? :P
    }
    Last edited by invitro; Aug 17th, 2006 at 06:38 PM. Reason: I said "1 value" rather then "1 row", this was confusing.
    ok, so... windows takes 1 minute to search for a file on my PC yet google.com takes 1 second to search the entire internet?

  2. #2
    Banned
    Join Date
    Nov 2005
    Posts
    2,367

    Re: Getting SQL data into Label not DataGrid

    Yeah, lose almost all of that (except the connection object). No datasets, no adapters, no binding and no girds.

    Code:
    		{
    			String strCategoryID;
    			String strArticleID;
    
    			strCategoryID = Request.QueryString["sci"];
    			strArticleID = Request.QueryString["sai"];
        
    			System.Data.SqlClient.SqlConnection sqlCon = new System.Data.SqlClient.SqlConnection("private");
    			System.Data.SqlClient.SqlCommand myCommand = new System.Data.SqlClient.SqlCommand("SELECT * FROM tblArticle WHERE tblArticle.charArticleID=@Article AND tblArticle.charCategoryID=@Category",sqlCon);
    	
    			try
    			{
    				sqlCon.Open();
    				myCommand.Parameters.Add("@Article", strArticleID);
    				myCommand.Parameters.Add("@Category", strCategoryID);
    				this.label1.text = myCommand.ExecuteScalar();
    			}
    			catch (System.Exception ex)
    			{
    				//Handle
    			}
    			finally
    			{
    				if (sqlCon.State == System.Data.ConnectionState.Open)
    				{
    					sqlCon.Close();
    				}
    			}

  3. #3

    Thread Starter
    Fanatic Member invitro's Avatar
    Join Date
    Jan 2000
    Location
    Outside your window
    Posts
    547

    Re: Getting SQL data into Label not DataGrid

    Thanks so much. I see what you are doing here, much easier. I will try this when I get home, thanks again.

    One question. You chose to use @Parameters rather then just placing the values into the command string. Is there a specific reason for this other then visual appeal?
    Last edited by invitro; Aug 10th, 2006 at 06:36 PM.
    ok, so... windows takes 1 minute to search for a file on my PC yet google.com takes 1 second to search the entire internet?

  4. #4
    Banned
    Join Date
    Nov 2005
    Posts
    2,367

    Re: [Resolved] Getting SQL data into Label not DataGrid

    it also prevents sql injection attacks. Say for instance soeone typed:

    ';shutdown--

    into one of the textboxes. The value would get processed as is. You would insert a bogus record and then the shutdown command would run (typically the db user wouldn't have this kind of elevated permission, but it's just an example). Paramaterizing your queries prevents this (it also takes are of special characters too).

  5. #5

    Thread Starter
    Fanatic Member invitro's Avatar
    Join Date
    Jan 2000
    Location
    Outside your window
    Posts
    547

    Re: Getting SQL data into Label not DataGrid

    Sorry about getting back to you so late, haven't had a chance to pick this up until today.

    I somewhat understand your method, but it does not work. The error I get is this:

    Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

    Compiler Error Message: CS0266: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)

    Source Error:

    Line 20: myCommand.Parameters.Add("@Article", strArticleID);
    Line 21: myCommand.Parameters.Add("@Category", strCategoryID);
    Line 22: label1.Text = myCommand.ExecuteScalar();
    Line 23: }
    Line 24: catch (System.Exception ex)


    Source File: \\shared.hosting.local\nfs\cust\2\36\70\707632\web\main.aspx Line: 22
    It seems that ExecuteScalar returns an object where as label1.text is obviously a string.

    I'm thinking you could probably do 'something' like
    object label;
    label = myCommand.ExecuteScalar();
    label1.text = label.value;
    ----------

    Regardless of how one would implement it, I don't think the way you are doing it would work. Looking at what you suggested, only one record would be retrieved from the database. Not only that, Executescalar only gets the first row in the first column, meaning the first value. (I could be confused here)

    I'm actually trying to get several values in the same row... the title, the body, and the image link. What im trying to get is not 1 value, but 1 full row and then pick the data fields that I need from that row (strArticle, strBody, strImage) etc.

    Sorry if I was unclear in my initial question,

    Thanks
    Last edited by invitro; Aug 17th, 2006 at 05:29 PM.
    ok, so... windows takes 1 minute to search for a file on my PC yet google.com takes 1 second to search the entire internet?

  6. #6
    Frenzied Member Fishcake's Avatar
    Join Date
    Feb 2001
    Location
    Derby, UK
    Posts
    1,092

    Re: Getting SQL data into Label not DataGrid

    All you need to do is add .ToString(). As the error says it cannot implicity convert an object to a string. Likewise if your scalar result was an int you'd use something like int i = Convert.ToInt32(myCommand.ExecuteScalar());

    Code:
    label1.Text = myCommand.ExecuteScalar().ToString();
    I know what you mean about DataGrid heavy tutorials it annoys me too.

  7. #7

    Thread Starter
    Fanatic Member invitro's Avatar
    Join Date
    Jan 2000
    Location
    Outside your window
    Posts
    547

    Thumbs up Re: Getting SQL data into Label not DataGrid

    Quote Originally Posted by Fishcake
    All you need to do is add .ToString(). As the error says it cannot implicity convert an object to a string. Likewise if your scalar result was an int you'd use something like int i = Convert.ToInt32(myCommand.ExecuteScalar());

    Code:
    label1.Text = myCommand.ExecuteScalar().ToString();
    I know what you mean about DataGrid heavy tutorials it annoys me too.

    Right, that works fine... but I want more then just the first row in the first column. Take a look at the second part of my last post, I'm trying to get 3 values from a row.

    Thanks for taking a look at this problem fishcake!
    ok, so... windows takes 1 minute to search for a file on my PC yet google.com takes 1 second to search the entire internet?

  8. #8
    Frenzied Member Fishcake's Avatar
    Join Date
    Feb 2001
    Location
    Derby, UK
    Posts
    1,092

    Re: Getting SQL data into Label not DataGrid

    ah ok sorry didn't read all the posts. ExecuteScalar will only return one result.

    Use a datareader instead which will loop through all rows in the returned data.
    Code:
            SqlDataReader dr;
            dr = command.ExecuteReader();
    
            while(dr.Read())
            {
                this.label1.Text = dr["Column1"].ToString();
                //or
                this.label2.Text = dr.GetString(dr.GetOrdinal("Column2"));
                //etc
            }
    Replace Column1 etc with the field names from your database and remember to close your datareader and database connection.

  9. #9

    Thread Starter
    Fanatic Member invitro's Avatar
    Join Date
    Jan 2000
    Location
    Outside your window
    Posts
    547

    Re: Getting SQL data into Label not DataGrid

    This is EXACTLY what I needed.

    Now to stuff this info into a c# class somehow...

    Thanks for all the help guys!
    ok, so... windows takes 1 minute to search for a file on my PC yet google.com takes 1 second to search the entire internet?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width