简体   繁体   English

如何通过按钮将数据从文本框传输到另一个 Winform 中的数据网格视图?

[英]How do I transfer data from a textbox to a data grid view in another winform via a button?

I have two forms, form1 and credentials.我有两个 forms、form1 和凭据。 I want the data in my textbox (can be filled by user) to be transferred to the data grid view in form1.我希望将文本框中的数据(可由用户填写)传输到 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.此外,在 form1 中,我希望我的标签中的数据也被传输到数据网格视图中,该视图也在 form1 中。 The labels I want to be transferred are: score, timer, level我要转移的标签是: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 和凭据的代码。

form1 source code: form1源代码:


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)
        {

        }
    }

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.我假设您有一个简单的对话框表单,该表单显示在您的 form1 凭据显示为模态。 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://docs.microsoft.com/en-us/dotnet/standard/events/ https://docs.microsoft.com/en-us/dotnet/standard/events/

If you want to transfer score, timer, level to datagridview and transfer Name from credentials to datagridview, you can refer to the following code:如果要将score、timer、level传给datagridview,将Name从credentials传给datagridview,可以参考以下代码:

Code in Form1: 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:以下是测试结果: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM