How can I only code this once and replicate c# - c#

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);
}
}

You can use the textbox as a parameter
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);
}
}
You should ensure that you also checking to make sure that the textbox isn't NULL

Related

How to change gridview row color by cell value?

I have cell name "MY_CELL"
I want to create if "MY_CELL" value is OK! then that Row color will be changed with GreenYellow.
private void gridView2_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
{
if (gridView2.RowCount > 0)
{
for (int i = 0; i < gridView2.DataRowCount; i++)
{
string text_sms2 = gridView2.GetRowCellValue(i, "MY_CELL").ToString();
if (text_sms2.Contains("ok"))
{
e.Appearance.BackColor = Color.GreenYellow;
}
else
{
e.Appearance.BackColor = Color.Red;
}
}
}
}
These code seems like works but all my rows color changed with "GreenYellow".
There's no need for the loop, since RowStyle event is raised for each individial row. Your code is setting apperence for each row according to the value in the last one.
Try this:
private void gridView2_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e) {
if (e.RowHandle >= 0) {
e.HighPriority = true;
var text = gridView2.GetRowCellDisplayText(e.RowHandle, view.Columns["MY_CELL"]);
if(text.Contains("ok") { // mind case sensitivity!!!
e.Appearance.BackColor = Color.GreenYellow;
}
else {
e.Appearance.BackColor = Color.Red;
}
}
}

How Can I do override behind orginal TextChange Method

Hi I wanna do override for all textBox But I wanna do TextChange method too
My TextChange Method is
private void TxtRozhaieKoleGharardad_OnTextChanged(object sender, TextChangedEventArgs e)
{
TryCatchBlock.ExecuteInTryCatch(() =>
{
if (TxtRozhaieKoleGharardad.Text != string.Empty)
{
int roz = Convert.ToInt32(TxtRozhaieKoleGharardad.Text);
PersianDate date = TxtTarikhShoro.SelectedDate.AddDays(roz);
TxtTarikhPayan.SelectedDate = date;
}
}, ref ResultMessageTryCatch);
}
and my override code is
class TextBox_JustNumbers : System.Windows.Controls.TextBox
{
protected override void OnTextChanged(TextChangedEventArgs e)
{
try
{
int caret = 0, lenghtText = 0;
if (this.CaretIndex == 0 || this.CaretIndex == this.Text.Length)
this.SelectionStart = this.Text.Length;
string value = this.Text.Replace(",", "");
decimal ul;
if (decimal.TryParse(value, out ul))
{
caret = this.CaretIndex;
lenghtText = this.Text.Length;
this.Text = string.Format("{0:#,#}", ul);
if (lenghtText + 1 == (this.Text.Length))
this.CaretIndex = caret + 1;
else
this.CaretIndex = caret;
}
}
catch
{
}
}
}
so when I run this code and change textBox Text Just do Override and don't go in TextChange Method How Can I fix It , I wanna do override behind orginal TextChange Method
I understand answer we must add
base.OnTextChanged(e);
after catch in override like this
...
if (lenghtText + 1 == (this.Text.Length))
this.CaretIndex = caret + 1;
else
this.CaretIndex = caret;
}
}
catch
{
}
base.OnTextChanged(e);
}

How to run CellEndEdit when a cell value changes in the DataGridView

The CellEndEdit event is running when I edit the datagridview cells, but when I print the data from the database to the DataGridView cell, CellEndEdit does not work:
dataGridView1.Rows[0].Cells[0].Value = "test";
How can I run CellEndEdit?
My code:
private void btnKaydet_Click(object sender, EventArgs e)
{
try
{
int index = 2;
int rc = gridView1.RowCount;
for (int i = 0; i < rc; i++)
{
index++;
string stk = gridView1.GetRowCellValue(i, "STOKKODU").ToString();
string beden = gridView1.GetRowCellValue(i, "BEDEN").ToString();
string mik = gridView1.GetRowCellValue(i, "MIKTARI_2").ToString();
dataGridView1.Rows[index].Cells[0].Value = stk;
dataGridView1.Rows[index].Cells[1].Value = beden;
dataGridView1.Rows[index].Cells[2].Value = mik;
}
ExcelProje.Save();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
object hucre = ExcelSayfa.Cells[dataGridView1.CurrentCell.RowIndex + 2, dataGridView1.CurrentCell.ColumnIndex + 1];
Excel.Range bolge = ExcelSayfa.get_Range(hucre, hucre);
bolge.Value2 = dataGridView1.CurrentCell.Value;
}

add total sum of rows in a datagridview in a label

I have a label as a Subtitle, in this label i want to display the number of rows in datagridview.
i added this line of code but it just returns a 0 not the amount of rows in the datagridview.
private void Form_Load(object sender, EventArgs e)
{
lblTitle.Text = _settings.set;
lblSubtitle.Text = dataGridView1.RowCount.ToString();
}
why is it displaying only a 0?
Requirement
DataGridView
Select Column Name Which you want to sum
A Label need in which you save the Result
SelectAmount is Label
private void function()
{
int SelectResult = 0;
if (DataSelector.RowCount != 0)
{
for (int i = 0; i < DataSelector.RowCount; i++)
{
bool value = false;
if (DataSelector.Rows[i].Cells["Select"].Value != null)
{
value = (bool)DataSelector.Rows[i].Cells["Select"].Value;
if (value)
{
int ar = 0;
bool r = int.TryParse(DataSelector.Rows[i].Cells["Paid"].Value.ToString(), out ar);
if (r)
{
SelectResult += ar;
}
}
}
}
}
SelectAmount.Text = SelectResult.ToString();
}
Use RowsAdded and RowsRemoved events for updating label with new value
public class YourForm
{
public YourForm()
{
InitializeComponent();
UpdateSubtitle(); // Display initial value
dataGridView1.RowsAdded += (sender, args) => UpdateSubtitle();
dataGridView1.RowsRemoved += (sender, args) => UpdateSubtitle();
}
private void UpdateSubtitle()
{
lblSubtitle.Text = dataGridView1.RowCount.ToString();
}
}

cannot set combo selected index when user type

I have a form with databound combobox, with dropstyle set as dropdown, so users could type in the combobox.
My problem is that when users type in the combobox and the value typed matches one of the values bound to the combobox it won't change the selectedindex, even though I've tried too. Instead, it sets the selected index to -1 (and thus the selected value is null).
Can anyone help? here's my code (one of my tries, i tried other approaches but none helped).
private void setCombo()
{
comboFromOther.DisplayMember = "tbl10_KupaID";
comboFromOther.ValueMember = "tbl10_KupaID";
comboFromOther.DataSource = dsKupotGemel.Tables[0];
}
private void comboToOther_TextChanged(object sender, EventArgs e)
{
comboDetail = changedComboText(2, comboToOther.Text);
textToOther.Text = comboDetail[0];
if (comboDetail[0] == "")
{
}
else
{
comboToOther.SelectedIndex = System.Int32.Parse(comboDetail[1]);
comboToOther.SelectedValue = System.Int32.Parse(comboDetail[2]);
}
}
private string[] changedComboText(int iComboType, string comboString)
{
if (groupCalculate.Visible == true)
{
groupCalculate.Visible = false;
}
string[] kupaDetail = new string[3];
kupaDetail[0] = "";
kupaDetail[1] = "";
kupaDetail[2] = "";
for (int i = 0; i <= dsKupotGemel.Tables[0].Rows.Count - 1; i++)
{
if (comboString == dsKupotGemel.Tables[0].Rows[i][0].ToString())
{
kupaDetail[0] = dsKupotGemel.Tables[0].Rows[i][1].ToString();
kupaDetail[1] = i.ToString();
kupaDetail[2] = comboString;
break;
}
else
{
}
}
return kupaDetail;
}
Maybe there is an error in your code?
Here is a working sample:
// Fields
private const string NameColumn = "Name";
private const string IdColumn = "ID";
private DataTable table;
Next, initialization
// Data source
table = new DataTable("SomeTable");
table.Columns.Add(NameColumn, typeof(string));
table.Columns.Add(IdColumn, typeof(int));
table.Rows.Add("First", 1);
table.Rows.Add("Second", 2);
table.Rows.Add("Third", 3);
table.Rows.Add("Last", 4);
// Combo box:
this.comboBox1.DisplayMember = NameColumn;
this.comboBox1.ValueMember = IdColumn;
this.comboBox1.DataSource = table;
this.comboBox1.DropDownStyle = ComboBoxStyle.DropDown;
this.comboBox1.TextChanged += comboBox1_TextChanged;
this.comboBox1.SelectedIndexChanged += this.comboBox1_SelectedIndexChanged;
Event handlers - TextChanged:
private void comboBox1_TextChanged(object sender, EventArgs e)
{
for (int i = 0; i < table.Rows.Count; i++)
{
if (table.Rows[i][NameColumn].ToString() == this.comboBox1.Text)
{
this.comboBox1.SelectedValue = table.Rows[i][IdColumn];
break;
}
}
}
Event handlers - SelectedIndexChanged:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// Do here what is required
}
With this code, as soon as user types full name of item into combo box, SelectedIndexChanged is invoked through TextChanged.
There is also such thing as AutoCompleteMode, AutoCompleteSource. Don't know where they fit into your application.

Categories