8 Replies - 3674 Views - Last Post: 12 October 2012 - 06:44 AM Rate Topic: -----

#1 jaArch  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 217
  • Joined: 23-March 10

Add values to a gridview

Posted 11 October 2012 - 07:32 AM

Hi:

Is it possible to add values to a gridview based on what the user enters in a textbox on a separate page where that value is stored in a session variable? Also, I was wondering if it's possible to add a value and that value increments based on the name the user enters in the textbox if the user has successfully completed a game? I'm just unsure as to how this is done - I have a gridview in place with the table loaded onto it.

Basically I just want to add values to the table from the name stored in a Session variable from a textbox and from the successful game play. I'm just unsure how to do this.

Is This A Good Question/Topic? 0
  • +

Replies To: Add values to a gridview

#2 h4nnib4l  Icon User is offline

  • The Noid
  • member icon

Reputation: 1181
  • View blog
  • Posts: 1,673
  • Joined: 24-August 11

Re: Add values to a gridview

Posted 11 October 2012 - 08:17 AM

I don't know exactly what that query would look like, because I don't know how your data structure looks, but you could pass that session variable to the query as a parameter, or use a switch on that value to assign a value to the parameter.

EDIT: If you can explain what you're doing with more detail, I can answer with more detail. :)

This post has been edited by h4nnib4l: 11 October 2012 - 08:18 AM

Was This Post Helpful? 0
  • +
  • -

#3 jaArch  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 217
  • Joined: 23-March 10

Re: Add values to a gridview

Posted 11 October 2012 - 08:33 AM

What I mean is that I hav a table for name and gamesplayed from the database and want to add the name the player has entered from a textbox into the table in the column 'name'. The value I wish to add to the next column (and should increase by one everytime the player successfully completes a game) is the amount of games played.

So far, I have it set as a session with the textbox and he parameter has been set in the query builder, but it doesn't seem to be adding the name. I have selected 'Session' and entered the name of the session in the field - which is 'name'
Was This Post Helpful? 0
  • +
  • -

#4 h4nnib4l  Icon User is offline

  • The Noid
  • member icon

Reputation: 1181
  • View blog
  • Posts: 1,673
  • Joined: 24-August 11

Re: Add values to a gridview

Posted 11 October 2012 - 09:06 AM

Okay. So the record doesn't get added unless/until the player successfully completes the game?

Also, if the player enters a name that is already in the table, will a successful completion create a new record, or will it be added to the existing records gamesplayed value?
Was This Post Helpful? 0
  • +
  • -

#5 jaArch  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 217
  • Joined: 23-March 10

Re: Add values to a gridview

Posted 11 October 2012 - 11:54 AM

For the first one: yes
For the second one: It will be added to the existing records gameplayed value.


I have already figured out the syntax for it as:

SELECT [Name], [GamesPlayed]
FROM [Players]
ORDER BY GamesPlayed DESC

UPDATE players
SET GamesPlayed = (GamesPlayed + 1)
WHERE name = @name

INSERT INTO players (Name,GamesPlayed)
VALUES (@name,1)

But the problem I'm having is that it won't add the name to it - I'm not sure how to do that when I have set the Session value to do that.

Will I need to use a databind for this?
Was This Post Helpful? 0
  • +
  • -

#6 h4nnib4l  Icon User is offline

  • The Noid
  • member icon

Reputation: 1181
  • View blog
  • Posts: 1,673
  • Joined: 24-August 11

Re: Add values to a gridview

Posted 11 October 2012 - 03:11 PM

After rereading your original post, I think that I know where you're going wrong. You don't need to be adding the session variable to the gridview; you need to be adding it to the database, and then refreshing your datasource and rebinding: the new result set will include the new record. As long as you're assigning your parameter correctly
var playerName = (string)Session["Name"];
myCmd.Parameters.AddWithValue("@name", name)


then that INSERT statement should work. (You should check that Session variable for null before you read it)

So, the process, in pseudocode, should kind of look like this:
-- player finishes game
-- pull player name from session
-- check DB for existence of player name
-- if player exists in database
--    increase GamesPlayed by 1
-- else
--    add player record to database

-- refresh your datasource for the GridView



I don't know how you're handling your datasource, so I can't be specific there. But to show the modified data set (with your new or updated record), you'll just run the SELECT query again, and bind the new results to the GridView. Are you having trouble getting data to show up in the GridView?
Was This Post Helpful? 0
  • +
  • -

#7 jaArch  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 217
  • Joined: 23-March 10

Re: Add values to a gridview

Posted 11 October 2012 - 03:26 PM

No, not having trouble getting it to show up in the gridview.

When you put 'myCmd' what is that referring to? Is that referring to the datasource associated with the connection?
Was This Post Helpful? 0
  • +
  • -

#8 jaArch  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 217
  • Joined: 23-March 10

Re: Add values to a gridview

Posted 11 October 2012 - 04:00 PM

This is the code I have used:

string name = (string)Session["name"];
                    SqlDS_Game.InsertParameters.Add("@name", name);
                    grdGame.DataBind();


For some reason it won't update the gridview and add the name to the table


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="guess_game.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>CO884 Lab 1 - Adam Graham</title>
    <style type="text/css">
        .style1
        {
            height: 80px;
            width: 86px;
            z-index: 1;
            left: 228px;
            top: 70px;
            position: absolute;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server" defaultbutton="btnGuess">
    <div>
    
        <h1>
            Number Guessing Game</h1>
        <p>
            <img 
                alt="" class="style1" src="Images/green-question-mark.jpg" /><asp:Label 
                ID="lblGuess" runat="server"></asp:Label>
        </p>
    
    </div>
    <asp:TextBox ID="txtGuess" runat="server" MaxLength="2" 
        ></asp:TextBox>
    <asp:Label ID="lblNum" runat="server"></asp:Label>
    &nbsp;&nbsp;
    <p>
        <asp:Button ID="btnGuess" runat="server" Text="Guess" 
            onclick="btnGuess_Click" />
        <asp:Button ID="btnGiveup" runat="server" Text="Give up" 
            onclick="btnGiveup_Click" />
        <asp:Button ID="btnNew" runat="server" Text="Start New Game" 
            onclick="btnNew_Click" />
    </p>
    <asp:Label ID="lblError" runat="server"></asp:Label>
    <br />
    <asp:Label ID="Label1" runat="server"></asp:Label>
    <br />
    <asp:GridView ID="grdGame" runat="server" AllowPaging="True" 
        AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="Name" 
        DataSourceID="SqlDS_Game">
        <Columns>
            <asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True" 
                SortExpression="Name" />
            <asp:BoundField DataField="GamesPlayed" HeaderText="GamesPlayed" 
                SortExpression="GamesPlayed" />

        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDS_Game" runat="server" 
        ConnectionString="<%$ ConnectionStrings:GuessGameConnectionString %>" 
        InsertCommand="INSERT INTO Players(Name, GamesPlayed) VALUES (@name, 1)" 
        SelectCommand="SELECT Name, GamesPlayed FROM Players ORDER BY GamesPlayed DESC" 
        UpdateCommand="UPDATE Players SET GamesPlayed = GamesPlayed + 1 WHERE (Name = @name)">
        <InsertParameters>
            <asp:Parameter Name="name" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="name" />
        </UpdateParameters>
    </asp:SqlDataSource>
    <br />
    </form>
</body>
</html>



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{


    protected void Page_Load(object sender, EventArgs e)
    {
        string name = (string)Session["name"];

        int year = (int)Session["year"];
   //     lblError.Text = "" + Session["name"];
   //   lblNum.Text = "" + Session["year"];

        if (year >= 19)
        {
            lblGuess.Text = "Guess a number between 1 and 50.";
        }
        else if (year < 19)
        {
            lblGuess.Text = "Guess a number between 1 and 20.";
        }
        int randomNum;
        btnNew.Visible = false;

        txtGuess.Focus();

        if (!IsPostBack)
        {
            if (year < 19)
            {
                Random number = new Random();
                randomNum = number.Next(1, 20);
                Session["number"] = randomNum;
                Session["Count"] = 0;
                //Label1.Text = "" + randomNum;
            }
            else if (year >= 19)
            {

                Random number = new Random();
                randomNum = number.Next(1, 50);
                Session["number"] = randomNum;
                Session["Count"] = 0;
               // Label1.Text = "" + randomNum;
            }
        }
    }
    protected void btnGuess_Click(object sender, EventArgs e)
    {
        int year = (int)Session["year"];
        int random = (int)Session["number"];
        int num;
        bool guess = Int32.TryParse(txtGuess.Text, out num);


        if (guess == false)
        {
            lblError.Text = "Invalid character. Must be a number";
        }

        if (guess == true)
        {
            if (year >= 19)

                if (num > 50 || num < 1)
                {
                    lblError.Text = "Number is not in range. Must be between 1 and 50.";
                }

                else  if (num < 51 || num > 1)
            {

                int count = (int)Session["Count"];
                count++;
                Session["Count"] = count;

                if (num == random)
                {

                    string name = (string)Session["name"];
                    SqlDS_Game.InsertParameters.Add("@name", name);
                    grdGame.DataBind();

                    lblError.Text = "Correct guess! It took you " + Session["Count"] + " guesses";
                    txtGuess.ReadOnly = true;
                    btnNew.Visible = true;
                    btnGuess.Enabled = false;
                    btnGiveup.Enabled = false;

                }
                else if (num != random)
                {
                    lblError.Text = "Incorrect guess. ";
                    if (num < random)
                    {
                        lblError.Text += "Guess higher";
                    }
                    else if (num > random)
                    {
                        lblError.Text += "Guess lower";
                    }
                }
            }
        }
    }


    protected void btnGiveup_Click(object sender, EventArgs e)
    {

        int random = (int)Session["number"];

        txtGuess.ReadOnly = true;
        btnNew.Visible = true;
        btnGuess.Enabled = false;
        btnGiveup.Enabled = false;

        lblError.Text = "Correct number was: " + random + ". Number of valid guesses made: " + Session["Count"];
    }
    protected void btnNew_Click(object sender, EventArgs e)
    {
        int year = (int)Session["year"];

        if (year < 19)
        {
            int randomNum;
            Random number = new Random();

            randomNum = number.Next(1, 20);
            Session["number"] = randomNum;
            Label1.Text = "" + randomNum;
            lblError.Text = "" + year;
            }

        else if (year >= 19)
        {
            int randomNum;
            Random number = new Random();

            randomNum = number.Next(1, 50);
            Session["number"] = randomNum;
            Label1.Text = "" + randomNum;
            lblError.Text = "" + year;
        }

        Session["Count"] = 0;
        lblError.Text = "";
        txtGuess.ReadOnly = false;
        txtGuess.Text = "";
        btnNew.Visible = false;
        btnGuess.Enabled = true;
        btnGiveup.Enabled = true;
    }
}


This post has been edited by jaArch: 11 October 2012 - 05:14 PM

Was This Post Helpful? 0
  • +
  • -

#9 h4nnib4l  Icon User is offline

  • The Noid
  • member icon

Reputation: 1181
  • View blog
  • Posts: 1,673
  • Joined: 24-August 11

Re: Add values to a gridview

Posted 12 October 2012 - 06:44 AM

Ahh, this all makes so much more sense to me now. My mistake. I was assuming you were using a SqlCommand object in code behing (that's what myCmd was), because that's how I always do things. I actually have almost no experience with the SqlDataProvider, but I'll see what I can do.

First off, it's bad programming practice to perform all of your actions in the event handlers (Page_Load and the button clicks). You should pull all of the code out of each event handler, place it in a separate method, and then call that method from the event handler.

Also, you're assigning name and year values out of Session, but on the first page load, those session variables wouldn't exist yet. I don't see a textbox on the form to take username, so I don't know where you're getting the name for the database write. I also noticed that after the game runs, the number I'm supposed to be guessing shows up right above the gridview, making it pretty easy to guess. ;)

I'm going to assume that there is no name in the session for now, because I don't ever see you take it from the user. So you'll need to create a textbox for the user to input their name. I'm going to call it txtName. Next, you'll need to create a method to do the update. I'll call it void UpdateDB(); you'll call this method from inside if (num == random). I removed these three lines

string name = (string)Session["name"];
SqlDS_Game.InsertParameters.Add("@name", name);
grdGame.DataBind();



from the If statement, because that logic will exists in UpdateDB(). UpdateDB() will look something like this:

void UpdateDB()
{
    string name = txtName.Text;
    bool exists = false;

    for(int i = 0; i < grdGame.Rows.Count - 1; i++)
    {
        if (grdGame.Rows[i].Cells[0].Text == name)
        {
            exists = true;
        }
    }

    if (exists)
    {
        // use an update, because the player exists
    }
    else
    {
        // use an insert, because the player doesn't exist
    }
}



That for loop, and the if/else that follows, is to determine whether or not the player already exists in the database, and then use either update or insert based on the results. I didn't test the for loop, so you might need to tweak it a little.

You'll need to do some research on performing updates and inserts against a SqlDataSource to figure out what goes inside the If and Else clause at the end of UpdateDB(); MSDN is always helpful, and I'm sure you can find a topic about it by searching the forums. I honestly don't know how to do it, because I never use the SqlDataSource, and I'm too lazy to figure it out myself (besides, it'll be good for you).
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1