0

I have two forms, form1 and credentials. I want the data in my textbox (can be filled by user) to be transferred to the data grid view in form1.

Also, in form1, I want the data in my labels to be also transferred into the data grid view, which is also in form1. The labels I want to be transferred are: score, timer, level

I have tried and research for multiple solutions, yet none can really solve my problem. however, I tried to combine the solutions from websites and here is what i can do that kind of make sense to me. following are the codes for form1 and credentials.

form1 source code:


public partial class Form1 : Form
{

    Snake mySnake;
    Board mainBoard;
    Rewards apples;

    string mode;
    Timer clock;
    int duration; //How long the game has been running
    int speed = 500; //500ms
    int score;
    int highscore;
    int level;

    public Form1()
    {
        InitializeComponent();
        //button2.Text = Char.ConvertFromUtf32(0x2197);

        //You don't have to worry about the auto-size
        this.AutoSize = true;       //The size of the Form will autoadjust.
        boardPanel.AutoSize = true; //The size of the panel grouping all the squares will auto-adjust

        //Set up the main board
        mainBoard = new Board(this);

        //Set up the game timer at the given speed
        clock = new Timer();
        clock.Interval = speed; //Set the clock to tick every 500ms
        clock.Tick += new EventHandler(refresh); //Call the refresh method at every tick to redraw the board and snake.

        duration = 0;
        score = 0;
        highscore = 0;
        level = 1;
        modeLBL.Text = mode;

        gotoNextLevel(level);

        scoresDGV.ColumnCount = 4;
        scoresDGV.Columns[0].HeaderText = "Name";
        scoresDGV.Columns[1].HeaderText = "Level";
        scoresDGV.Columns[2].HeaderText = "Score";
        scoresDGV.Columns[3].HeaderText = "Timer";
        scoresDGV.AllowUserToAddRows = false;
        scoresDGV.AllowUserToDeleteRows = false;
        scoresDGV.MultiSelect = false;
        scoresDGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        scoresDGV.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    }

    private void refresh(Object myObject, EventArgs myEventArgs)
    {
        //increment the duration by amount of time that has passed
        //this method is called every speed millisecond
        duration += speed;
        timerLBL.Text = Convert.ToString(duration / 1000); //Show time passed

        //Check if snke is biting itself. If so, call GameOver.
        if (mySnake.checkEatItself() == true)
        {
            GameOver();
        }
        else if (apples.checkIFSnakeHeadEatApple( mySnake.getHeadPosition()) == true)
        {
            score += apples.eatAppleAtPostion(mySnake.getHeadPosition());

            scoreLBL.Text = Convert.ToString(score);


            if (apples.noMoreApples() == true)
            {
                clock.Stop();
                level++;
                levelLBL.Text = Convert.ToString(level);
                gotoNextLevel(level);
                MessageBox.Show("Press the start button to go to Level " + level, "Congrats");
            }
            else
            {
                //Length the snake and continue with the Game
                mySnake.extendBody();
            }
        }

        if (score > highscore)
        {
            highscoreLBL.Text = Convert.ToString(highscore);
        }
    }

    private void startBTN_Click(object sender, EventArgs e)
    {
        clock.Start();
    }
    private void pauseBTN_Click(object sender, EventArgs e)
    {
        clock.Stop();
    }
    private void restartBTN_Click(object sender, EventArgs e)  //snapBTN
    {
        duration = 0;
        mySnake.draw();
    }
    private void backBTN_Click(object sender, EventArgs e)
    {
        // hides the form from the user. in this case, the program hides the HowToPlay form
        this.Hide();
        MainMenu mM = new MainMenu();
        mM.ShowDialog();
        this.Close();
    }

    private void GameOver()
    {
        clock.Stop();
        MessageBox.Show("Your time taken is " + duration/1000 + " seconds. Bye Bye", "Game Over");
        this.Close();

        addCurrentScoresToDatabase();
        //updateScoreBoard();
    }
    private void modeLBL_Click(object sender, EventArgs e)
    {

    }
    private void addCurrentScoresToDatabase()
    {
        Credentials c = new Credentials();
        c.ShowDialog();
    }

}

credentials source code:
public partial class Credentials : Form
    {
        public static string SetValueForName = "";
        public Credentials()
        {
            InitializeComponent();
        }
        private void saveBTN_Click(object sender, EventArgs e)
        {
            SetValueForName = enternameTB.Text;

            Form1 frm1 = new Form1();
            frm1.Show();
        }
        private void cancelBTN_Click(object sender, EventArgs e)
        {

        }
    }
davidsbro
  • 2,761
  • 4
  • 23
  • 33
  • What's the issue you are facing? https://stackoverflow.com/questions/1559770/send-values-from-one-form-to-another-form – Chetan Jan 24 '22 at 12:18
  • https://www.c-sharpcorner.com/UploadFile/834980/how-to-pass-data-from-one-form-to-other-form-in-windows-form/ – Chetan Jan 24 '22 at 12:18

2 Answers2

0

Because part of your code is made in the designer (and not shown here in your post) it is difficult to understand how it works. I assume you have a simple dialog form which is shown in your form1 Credentials is shown modal. So if you have some properties in your credentials dialog, you may data transfer via the properties.

   private void addCurrentScoresToDatabase()
    {
        Credentials c = new Credentials();
    // initialize c here
        c.ShowDialog();
    // read data from c here
    }

If you want get data from the credential dialog while it is shown, you should use events. https://learn.microsoft.com/en-us/dotnet/standard/events/

jokn
  • 44
  • 7
0

If you want to transfer score, timer, level to datagridview and transfer Name from credentials to datagridview, you can refer to the following code:

Code in Form1:

int index;
public void AddScore_Click(object sender, EventArgs e)
    {
        index = scoresDGV.Rows.Add();
        scoresDGV.Rows[index].Cells[1].Value = label1.Text; 
        scoresDGV.Rows[index].Cells[2].Value = label2.Text; 
        scoresDGV.Rows[index].Cells[3].Value = label3.Text;
        Credentials c = new Credentials();
        c.FormClosed += c_FormClosed;
        c.Show();
    }
void c_FormClosed(object sender, FormClosedEventArgs e)
    {
        scoresDGV.Rows[index].Cells[0].Value = Credentials.SetValueForName;
    }

Code in Credentials:

public partial class Credentials : Form
{
    public static string SetValueForName = "";
    public Credentials()
    {
        InitializeComponent();
    }

    private void saveBTN_Click(object sender, EventArgs e)
    {
        SetValueForName = enternameTB.Text;
        this.Close();
    }
}

Here is the test result: enter image description here

Jingmiao Xu-MSFT
  • 2,076
  • 1
  • 3
  • 10