如何以不同的形式将文本框数据传递到datagridview [英] How to pass textbox data to a datagridview in different forms

查看:221
本文介绍了如何以不同的形式将文本框数据传递到datagridview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种形式:



第一个表单(XML Data Loader)包含一个具有六列(名称,宽度,高度,长度,重量,加载)的DataGridView容量)



XML数据加载器还有一个按钮,当按下时打开一个新窗体窗口(添加新车)。
添加新车有六个文本框,其中列车数据由用户输入。



目标是让用户能够单击保存按钮添加新车,数据将被推入XML Data Loader中的DataGridView的新行,但我遇到一个问题,实际上找到了一种方法。我发现的其他一切都假定DataGridView是通过一个数据库填充的,但是我的用户输入填充了。






  public partial class XMLDataLoader:Form 
{
public XMLDataLoader()
{
InitializeComponent();
}

private void buttonAddCar_Click(object sender,EventArgs e)
{
AddNewCar addNewCar = new AddNewCar();
addNewCar.Show();
}
}



DialogResult.Cancel 在表单设计器中,当用户单击它时,它会将该值分配给 Form.DialogResult ,这将导致窗口关闭, ShowDialog 返回 DialogResult.Cancel



另一种可以做到这一点的方法是声明一个简单的类,其中包含所有的汽车制作数据: NewName 宽度等编写一个 ShowDialog()的重载,返回该类型,或者引用该类型并返回 bool (对于OK,为true)。如果用户取消它返回null或false;如果用户单击确定并通过验证,它将返回该类的实例,或者在引用版本中填充传入的引用的成员,然后返回true。



如果您已经有一个代表Car(从实体框架或其他)的类,那么您只需使用它。



但是我上面描述的方式与内置的WinForms对话框(如 FileOpen 等)的使用是一致的上。在WinForms,MFC,WPF等环境中工作时,我的试金石是框架会做什么?几乎总是正确的答案,因为a)成功的框架往往设计得很好被无法访问其内部人员或咨询其实施者的成功使用),以及b)与代码交互的任何人都会知道预期的内容,因为他已经知道框架的做法。



每次我使用第三方代码,认为它比框架更聪明,我不禁要注意多少dumber。


I have two forms:

The first form (XML Data Loader) contains a DataGridView with six columns (Name, Width, Height, Length, Dead Weight, Load Capacity)

XML Data Loader also has a button on it, which when pressed opens a new forms window (Add New Car). Add New Car has six textboxes where train car data is input by a user.

The goal is for the user to be able to click the Save button on Add New Car and the data will be pushed into a new row in the DataGridView on XML Data Loader, but I am having an issue with actually finding a way to do this. Everything else I've found assumes that DataGridViews are being populated through a database, but mine is user-input populated.


public partial class XMLDataLoader : Form
{
    public XMLDataLoader()
    {
        InitializeComponent();
    }

    private void buttonAddCar_Click(object sender, EventArgs e)
    {
        AddNewCar addNewCar = new AddNewCar();
        addNewCar.Show();
    }
}

public partial class AddNewCar : Form
{
    public AddNewCar()
    {
        InitializeComponent();
    }

    private void buttonNewSave_Click(object sender, EventArgs e)
    {
        //Check that all textboxes have some kind of entry
        //ToDo: check the type of data so that only numbers are entered into non-name categories
        if(textBoxNewName.TextLength < 1)
        {
            MessageBox.Show("Please enter a train name!");
        }
        if (textBoxNewWidth.TextLength < 1)
        {
            MessageBox.Show("Please enter a train width!");
        }
        if (textBoxNewHeight.TextLength < 1)
        {
            MessageBox.Show("Please enter a train height!");
        }
        if (textBoxNewLength.TextLength < 1)
        {
            MessageBox.Show("Please enter a train length!");
        }
        if (textBoxNewDeadWeight.TextLength < 1)
        {
            MessageBox.Show("Please enter a train dead weight!");
        }
        if (textBoxNewLoadCapacity.TextLength < 1)
        {
            MessageBox.Show("Please enter a train load capacity!");
        }

        //Save all data input by user to create a new train momentarily
        var newTrainName = textBoxNewName.Text;
        var newTrainWidth = textBoxNewWidth.Text;
        var newTrainHeight = textBoxNewHeight.Text;
        var newTrainLength = textBoxNewLength.Text;
        var newTrainDeadWeight = textBoxNewDeadWeight.Text;
        var newTrainLoadCapacity = textBoxNewLoadCapacity.Text;
    }
}

解决方案

First, use ShowDialog() instead of Show(). That way, you will still be in buttonAddCar_Click when the AddNewCar dialog closes. The way your code is now, buttonAddCar_Click will exit while AddNewCar is still visible, and your main window will have lost all contact with the instance of AddNewCar that you created.

Secondly, you need to expose the text box values to the caller. So after the dialog closes, addNewCar.textBoxNewName.Text will contain the string the user typed into the New Name TextBox. But by default that's not public. So add a bunch of properties to expose the values:

public String NewName { get { return textBoxNewName.Text; } }

In buttonAddCar_Click after the call to ShowDialog(), you can do whatever you like with the exposed Text properties of all those TextBoxes.

I don't do winforms every day now, so it's possible that textBoxNewName.Text may throw an exception if you touch it after the form closes. Easy fix! Declare the public properties as regular properties instead of get-only accessors...

public String NewName { get; protected set; }

...and assign them their values in the OK click event when the user's input passes validation. Which is our next topic.

Lastly, making the user click on (potentially) six popups in succession is enough to make him commit suicide. Instead, I'd recommend declaring a string variable called message and concatenating:

    string message = "";
    if(textBoxNewName.TextLength < 1)
    {
        message += "Please enter a train name!\n"
    }
    if (textBoxNewWidth.TextLength < 1)
    {
        message += "Please enter a train width!\n";
    }

    //  ...etc....

    if (!String.IsNullOrWhiteSpace(message))
    {
        MessageBox.Show(message);
    }
    else
    {
        NewName = textBoxNewName.Text;
        //  ...and so on for the other five properties. 

        //  This will close the form and cause ShowDialog() to
        //  return DialogResult.OK
        DialogResult = DialogResult.OK;
    }

Form.DialogResult is a useful adjunct to Form.ShowDialog().

If you have a Cancel button, it doesn't even need a Click method. Just set that Button's DialogResult property to DialogResult.Cancel in the form designer, and it'll assign that value to Form.DialogResult when the user clicks it, which will cause the window to close and ShowDialog to return DialogResult.Cancel.

Another way you could do this is declare a simple class which has all the car-creation data in it: NewName, Width, etc. Write an overload of ShowDialog() which returns that type, or which takes a reference to that type and returns bool (true for OK). If user cancels it returns null or false; if user clicks OK and passes validation, it returns an instance of that class, or in the reference version, populates the members of the reference that was passed in, and then returns true.

If you already have a class which represents a Car (from Entity Framework or whatever), you would just use that.

But the way I've described above is consistent with usage in built-in WinForms dialogs like FileOpen and so on. My touchstone when working in any environment like WinForms, MFC, WPF, etc. is What Would the Framework Do? That's almost invariably the right answer, because a) successful frameworks tend to be reasonably well designed (they are used successfully by people who can't access their internals or consult their implementors), and b) anybody who interacts your code will know exactly what to expect because he already knows the framework's way of doing things.

Every time I use third party code that thinks it's smarter than the framework, I can't help noticing how much dumber it is.

这篇关于如何以不同的形式将文本框数据传递到datagridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆