I am new to C# and classes. I was testing on making a datagridview where the user can right click and a contextmenustrip pops. Now my question is the following.
I made my code to add the text to the textbox and increase the textbox if it is not empty.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);
}
}
Is there a way to only have this code only 1 time and call it every time I need it. So that I only have to change the textboxes.Text? Otherwise I need to copy and paste this code more than 10 times.
What I tried
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);
}
}
Fix
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);
}
}