我是C#和类的新手。我正在做一个datagridview的测试,用户可以在其中单击鼠标右键,然后弹出contextmenustrip。现在,我的问题如下。
我编写了代码,将文本添加到文本框中,如果文本不为空,则增加文本框。With help from this post.
private void TsmItem_Click(object sender, EventArgs e)
{
int rowindex = dgvResults.CurrentCell.RowIndex;
int columnindex = dgvResults.CurrentCell.ColumnIndex;
double resultText;
if (string.IsNullOrEmpty(Textbox.Text))
{
Textbox.Text = dgvResults.Rows[rowindex].Cells[columnindex].Value.ToString();
}
else
{
string selectedCell;
selectedCell = dgvResults.Rows[rowindex].Cells[columnindex].Value.ToString();
ResultText = Convert.ToDouble(Textbox.Text) + Convert.ToDouble(selectedCell);
Textbox.Text = Convert.ToString(ResultText);
}
}
有没有办法只让这段代码1次,并在每次需要时调用它。这样我只需要更改textboxes.Text?否则,我需要将此代码复制并粘贴10次以上。
我尝试过的事情
private void TsmItem_Click(object sender, EventArgs e)
{
Textbox.Text = RightMouseClick(Textbox.Text);
}
private void RightMouseClick(string txtResult)
{
int rowindex = dgvResults.CurrentCell.RowIndex;
int columnindex = dgvResults.CurrentCell.ColumnIndex;
if (string.IsNullOrEmpty(txtResult))
{
txtResult = dgvResults.Rows[rowindex].Cells[columnindex].Value.ToString();
}
else
{
string selectedCell;
double resultText;
selectedCell = dgvResults.Rows[rowindex].Cells[columnindex].Value.ToString();
resultaat = Convert.ToDouble(txtResult) + Convert.ToDouble(selectedCell);
txtResult = Convert.ToString(resultText);
}
}
修复
private string RightMouseClick(TextBox txtResult)
{
int rowindex = dgvResults.CurrentCell.RowIndex;
int columnindex = dgvResults.CurrentCell.ColumnIndex;
if (string.IsNullOrEmpty(txtResult.Text))
{
return txtResult.Text = dgvResults.Rows[rowindex].Cells[columnindex].Value.ToString();
}
else
{
string selectedCell;
double resultaat;
selectedCell = dgvResults.Rows[rowindex].Cells[columnindex].Value.ToString();
resultaat = Convert.ToDouble(txtResult.Text) + Convert.ToDouble(selectedCell);
return txtResult.Text = Convert.ToString(resultaat);
}
}
答案 0 :(得分:1)
您可以将文本框用作参数
private void RightMouseClick(TextBox txtBox)
{
int rowindex = dgvResults.CurrentCell.RowIndex;
int columnindex = dgvResults.CurrentCell.ColumnIndex;
if (string.IsNullOrEmpty(txtResult))
{
txtBox.Text = dgvResults.Rows[rowindex].Cells[columnindex].Value.ToString();
}
else
{
string selectedCell;
double resultText;
selectedCell = dgvResults.Rows[rowindex].Cells[columnindex].Value.ToString();
resultaat = Convert.ToDouble(txtBox.Text) + Convert.ToDouble(selectedCell);
txtBox.Text = Convert.ToString(resultText);
}
}
您还应确保还检查以确保文本框不是NULL