我正在调用一个模式表格(ss
),其中显示了给定搜索条件的所有股票代码。用户选择一个项目
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
selectedStockDescription = dgv_StckSrchRes.Rows[e.RowIndex].Cells[1].Value.ToString();
selectedStockCode = dgv_StckSrchRes.Rows[e.RowIndex].Cells[0].Value.ToString();
DialogResult result = MessageBox.Show(
(selectedStockDescription),
"Add this item to the order?",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
stockCode = selectedStockCode;
stockDescription = selectedStockDescription;
this.Close();
}
else if (result == DialogResult.No)
{
this.Focus();
}
else if (result == DialogResult.Cancel)
{
this.Close();
}
}
和以下两个公共字符串以 modal形式设置:
public string stockCode { get; set; }
public string stockDescription { get; set; }
在我的父表格中,我将这些值分配给在类级别初始化的两个变量。
using (StockSearch ss = new StockSearch(selectedDept, txb_StockCode.Text))
{
if (ss.ShowDialog() != DialogResult.Cancel)
stckCd = ss.stockCode;
stockDescription = ss.stockDescription;
SetFormProperties();
PopulateStockInformation();
GetLeadTimes();
}
但是仅设置stockDescription
变量。即使填充了右侧的值stckCd
,null
仍为ss.stockCode
。它只是没有为stckCd
分配值,我需要它才能访问应用程序中其他位置的值。我尝试用一个值初始化它们,但不能解决这个问题。
任何人都可以开导我吗?
答案 0 :(得分:0)
问题出在StockSearch
(模态形式)一侧:关闭StockSearch
时应设置DialogResult
:有两个 这里可能的关闭-取消(默认行为)和确定。
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) {
selectedStockDescription = dgv_StckSrchRes.Rows[e.RowIndex].Cells[1].Value.ToString();
selectedStockCode = dgv_StckSrchRes.Rows[e.RowIndex].Cells[0].Value.ToString();
DialogResult result = MessageBox.Show(
(selectedStockDescription),
"Add this item to the order?",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question);
if (result == DialogResult.Yes) {
// Confirmed: close the form WITH the choice made (DialogResult.OK)
stockCode = selectedStockCode;
stockDescription = selectedStockDescription;
// this.Close(); // <- cause of the misbehaviour
this.DialogResult = DialogResult.OK; // <- not Close (with cancel) but with OK
}
else if (result == DialogResult.No)
// Not confirmed: keep on selecting
this.Focus();
else // no need in "if": all the rest is Cancel
// Cancellation: close the form WITHOUT choice (DialogResult.Cancel)
this.Close(); // <- Close with DialogResult.Cancel
}
在父表单方面
using (StockSearch ss = new StockSearch(selectedDept, txb_StockCode.Text)) {
if (ss.ShowDialog() != DialogResult.Cancel) {
stckCd = ss.stockCode;
// You should not change stockDescription on DialogResult.Cancel
stockDescription = ss.stockDescription;
}
//TODO: it seems that these three calls should be within if as well
SetFormProperties();
PopulateStockInformation();
GetLeadTimes();
}