将数据从文本框传递到datagridview

时间:2017-04-05 22:17:56

标签: c# sql winforms visual-studio datagridview

我在运行Windows应用程序的Visual Studio中工作。

我想知道我是否可以从DataGridView填充TextBox,这本身就是传递值?

例如,用户将从对话框表单中搜索患者。他们选择的患者姓名将在我的主表单上填充TextBox。我希望选定的患者在测试历史记录之前填充选项卡中该主要表单上的DataGridView

这是否可能,如果是这样,我将如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

有可能。我建议设置某种数据绑定。更具体地说,您将需要一些维护状态和数据的类与您的控件以及可能的对话框形式绑定。我不知道你在寻找多少,所以这可能会过分但我会建议这样的事情:

public class MainForm : Form
{
    public MainForm(StateManager stateManager)
    {
        _stateManager = stateManager;

        //data binding for your text box
        txtPatientName.DataBindings.Add(nameof(txtPatientName.Text), stateManager, nameof(stateManager.PatientName));

        //data binding for your grid
        historyGrid.DataSource = stateManager.History;
    }

    private void btnShowForm_Click(object sender, EventArgs e)
    {
        using(var form = new DialogForm())
        {
            var result = form.ShowDialog();
            if(result == DialogResult.Ok)
            {
                _stateManager.UpdatePatient(form.InputPatientName);
            }
        }
    }

    private StateManager _stateManager;
}

//this is the form where you enter the patient name
public class DialogForm : Form
{
    //this holds the value where the patient's name is entered on the form
    public string InputPatientName { get; set; }
}

//this class maintains your state
public class StateManager : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public string PatientName
    {
        get { return _patientName; }
        set 
        {
            _patientName = value;
            OnPropertyChanged(nameof(PatientName));
        }
    }

    public BindingList<MedicalHistoryItems> History => _history ?? (_history = new BindingList<MedicalHistoryItems>());

    public void UpdatePatient(string patientName)
    {
        History.Clear();

        var historyRetriever = new HistoryRetriever();
        History.AddRange(historyRetriever.RetrieveHistory(patientName));
    }

    private void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(propertyName);
    }

    private BindingList<MedicalHistoryItems> _history;
    private string _patientName;
}