How Check combobox c# not select same index - c#

1 Choose Normal Or special
2 Choose special Price+5
3 Choose Normal Price-5
4 But Choose same is Price double
private void comboType_SelectedIndexChanged(object sender, EventArgs e)
{
if (lblProID.Text == "")
{
//MessageBox.Show("Please Find Food");
txtAmount.Text = "";
buttonFind.Focus();
}
else if (comboType.SelectedIndex == 1)
{
lblProCost.Text = (Convert.ToDouble(lblProCost.Text) + (5)).ToString("#,##0.00");
}
else
{
lblProCost.Text = (Convert.ToDouble(lblProCost.Text) - (5)).ToString("#,##0.00");
}
}
Logic IF Select Normal (Price -5)
else Select special (Price +5)
I want to check If Select same index not Sum price
Or You have idea New For Help Me ! Thank

The easiest way would be to create a variable / property on the form level that stores the previous combobox selected index value and you could compare comboType.selectedIndex with that variable - if the same do nothing, else do something and overwrite this variable.
The other way is to derive your own class from the combobox and implement the variable on the combobox devided class level + add a method that checks if selected index is the same - return true if not return false but also overwrite the old selected index value.

Related

how to replace the values in List index C#?

I am using DataGridView in C# being civil engineer.
I want the values from a particular row. If the same value appears in a row, I want to display a message. For example, if 1 appears multiple time in a row, i want to display a message on every 1.
Here is how I am doing it:
private void button4_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView2.ColumnCount - 1; i++)
{
if (CategoryCLO[i] == 1)
{
MessageBox.Show("Here i am");
}
else
{
MessageBox.Show("I am not");
}
}
}
private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == 1)
{
CategoryCLO.Add(int.Parse(
dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()));
}
}
Problem:
It works right only one time. If a user replaces a value in a cell in DataGridView, it adds up another value corresponding to the newly added index of list.
Explanation:
The problem is that when user changes value in DataGridView, it got adds up in the list, thus increase the index of list , I want that index of list should be fix to the column index. and any change in particular cell , should change in that particular index rather than adding up.
Question:
I want that value should be placed in the previous index rather than creating new. In short, I want the indexes of list should be fixed to column number. How can I do it? any direction?
Note: Column numbers are variable depending upon the user

Creating a sudoku. Should I use a while statement for this code?

I'm making a sudoku in Windows Form Application.
I have 81 textboxes and I have named them all textBox1a, textBox1b... textBox2a, textBox2b...
I want to make it so that if any of the textboxes, in any of the rows, is equal to any other textbox in the same row, then both will get the background color red while the textboxes are equal.
I tried using this code just for test:
private void textBox1a_TextChanged_1(object sender, EventArgs e)
{
while (textBox1a.Text == textBox1b.Text)
{
textBox1a.BackColor = System.Drawing.Color.Red;
textBox1b.BackColor = System.Drawing.Color.Red;
}
It didn't work, and I don't know where I should put all this code, I know I shouldn't have it in the textboxes.
Should I use a code similar to this or is it totally wrong?
You want to iterate over the collection of text boxes just once, comparing it to those that haven't yet been compared against. If you have your textboxes in an array (let's call it textBoxes), and know which one was just changed (e.g. from the textChanged handler), you could do:
void highlightDuplicates(int i) // i is the index of the box that was changed
{
int iVal = textBoxes[i].Text;
for (int j = 0; j < 82; j++)
{
// don't compare to self
if (i == j) return;
if (textBoxes[j].Text == iVal)
{
textBoxes[i].BackgroundColor = System.Drawing.Color.Red;
textBoxes[j].BackgroundColor = System.Drawing.Color.Red;
}
}
}
If you wanted to get fancier, you could put your data in something like: Dictionary<int, TextBox>, where the key is the value and the TextBox is a reference to the text box with that value. Then you can quickly test for duplicate values with Dictionary.Contains() and color the matching text box by getting its value.
I think your current code would result in an infinite loop. The textboxes' values can't change while you are still in the event handler, so that loop would never exit.
If all of your boxes are named according to one convention, you could do something like this. More than one input can use the same handler, so you can just assign this handler to all the boxes.
The following code is not tested and may contain errors
private void textBox_TextChanged(object sender, EventArgs e){
var thisBox = sender as TextBox;
//given name like "textBox1a"
var boxNumber = thisBox.Name.SubString(7,1);
var boxLetter = thisBox.Name.SubString(8,1);
//numbers (horizontal?)
for(int i = 1; i<=9; i++){
if(i.ToString() == boxNumber)
continue; //don't compare to self
var otherBox = Page.FindControl("textBox" + i + boxLetter) as TextBox;
if (otherBox.Text == thisBox.Text)
{
thisBox.BackColor = System.Drawing.Color.Red;
otherBox.BackColor = System.Drawing.Color.Red;
}
}
//letters (vertical?)
for(int i = 1; i<=9; i++){
var j = ConvertNumberToLetter(i); //up to you how to do this
if(j == boxLetter)
continue; //don't compare to self
var otherBox = Page.FindControl("textBox" + boxNumber + j) as TextBox;
if (otherBox.Text == thisBox.Text)
{
thisBox.BackColor = System.Drawing.Color.Red;
otherBox.BackColor = System.Drawing.Color.Red;
}
}
}
I believe you will be more effective if create an Array (or a List) of Integers and compare them in memory, against compare them in UI (User Interface).
For instance, you could:
1) Create an Array of 81 integers.
2) Everytime the user input a new number, you search for it in that Array. If found, set the textbox as RED, otherwise, add the new value to that array.
3) The ENTER event may be allocated fot the entire Textboxes (utilize the Handles keyword with all Textboxes; like handles Text1.enter, Text2.enter, Text3.enter ... and so forth)
Something like:
int[] NumbersByUser = new int[81];
Private Sub Textbox1.Enter(sender as object, e as EventArgs) handles Textbox1.Enter, Textbox2.Enter, Textbox3.enter ...
int UserEntry = Convert.ToInt32(Sender.text);
int ValorSelecionado = Array.Find(NumbersByUser, Z => (Z == UserEntry));
if (ValorSelecionado > 0) {
Sender.forecolor = Red;
}
else
{
NumbersByUser(Index) = UserEntry;
}
You should have a 2 dimensional array of numbers (could be one dimensional, but 2 makes more sense) let's assume its called Values. I suggest that you have each textbox have a incrementing number (starting top left, going right, then next row). Now you can do the following:
All TextBox Changed events can point to the same function. The function then takes the tag to figure out the position in the 2dim array. (X coordinate is TAG % 9 and Y coordinate is TAG / 9)
In the callback you can loop over the textboxes and colorize all boxes as you like. First do the "check row" loop (pseudo code)
var currentTextBox = ((TextBox)sender)
var x = ((int)currentTextBox.Tag) % 9
var y = ((int)currentTextBox.Tag) / 9
// First assign the current value to the backing store
Values[currentTextBox] = int.parse(currentTextBox.Text)
// assuming variable x holding the column and y holding the row of current box
// Array to hold the status of a number (is it already used?)
bool isUsed[9] = {false, false, ...}
for(int col = 0; col <= 9; i++)
{
// do not compare with self
if(col == x) continue;
isUsed[textBox] = true;
}
// now we have the status of all other boxes
if( isUsed[Values[x,y]] ) currentTextBox.Background = Red else currentTextBox.Background = Green
// now repeat the procedure for the column iterating the rows and for the blocks
I would suggest a dynamic approach to this. Consider each board item as a cell (this would be it's own class). The class would contain a numeric value and other properties that could be useful (i.e. a list of possible values).
You would then create 3 collections of the cells, these would be:
A collection of rows of 9 cells (for tracking each row)
A collection of columns of 9 cells (for tracking each column)
A collection of 3x3 cells
These collections would share references - each cell object would appear once in each collection. Each cell could also contain a reference to each of the 3 collections.
Now, when a cell value is changed, you can get references to each of the 3 collections and then apply a standard set of Sudoku logic against any of those collections.
You then have some display logic that can walk the boards of cells and output to the display (your View) your values.
Enjoy - this is a fun project.

How to Create combo box to auto fill while user type the spellings inside the combo Box in C#

I have a ComboBox in my Windows Form that I can fill with data from a database. However, I can't fill the ComboBox when the user types letters inside it.
As an example, when the user types the letter "R" inside the ComboBox, it drops down and shows all the possible values with the letter "R".
How can I autofill the ComboBox when the user types something inside it?
Set yourComboBox.AutoCompleteSource to AutoCompleteSource.ListItems; (if your yourComboBox.Items was already filled from the database)
Set yourComboBox.AutoCompleteMode to SuggestAppend
You would have to tie in with the KeyUp event on the comboBox, and, using comboBox.Text, filter the comboBox.Items collection to only show containing typed characters. You would also need to force the comboBox window to dropdown as well.
Hope this helps you:
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
string strToFind;
// if first char
if (lastChar == 0)
strToFind = ch.ToString();
else
strToFind = lastChar.ToString() + ch;
// set first char
lastChar = ch;
// find first item that exactly like strToFind
int idx = comboBox1.FindStringExact(strToFind);
// if not found, find first item that start with strToFind
if (idx == -1) idx = comboBox1.FindString(strToFind);
if (idx == -1) return;
comboBox1.SelectedIndex = idx;
e.Handled = true;
}
void comboBox1_GotFocus(object sender, EventArgs e)
{
// remove last char before select new item
lastChar = (char) 0;
}
From here

Looping Radio Button Check in Visual C#

I'm new to C#, trying to make a program that is essentially a survey with 30 questions that are answered by selecting one of five radio buttons (Strongly Disagree, Disagree...Strongly Agree, etc).
I have set up a small "block" of code that will check which radio button is checked for the question and assign a value to an array (see below).
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonScore_Click(object sender, EventArgs e)
{
this.textBoxScoreOutput.Text = " ";
int[] score = new int[2]; // Declares the integer of score and sets it to a value of zero
// Question 1
if (radioButtonSD1.Checked == true) // If Strongly Disagree checked give score a value of 1
score[0] = 1;
else if (radioButtonD1.Checked == true) // If Disagree checked give score a value of 2
score[0] = 2;
else if (radioButtonNS1.Checked == true) // If Not Sure checked give score a value of 3
score[0] = 3;
else if (radioButtonA1.Checked == true) // If Agree checked give score a value of 4
score[0] = 4;
else if (radioButtonSA1.Checked == true) // If Strongly Agree is checked give score a value of 5
score[0] = 5;
// Question 2
if (radioButtonSD2.Checked == true) // If Strongly Disagree checked give score a value of 1
score[1] = 1;
else if (radioButtonD2.Checked == true) // If Disagree checked give score a value of 2
score[1] = 2;
else if (radioButtonNS2.Checked == true) // If Not Sure checked give score a value of 3
score[1] = 3;
else if (radioButtonA2.Checked == true) // If Agree checked give score a value of 4
score[1] = 4;
else if (radioButtonSA2.Checked == true) // If Strongly Agree is checked give score a value of 5
score[1] = 5;
// Output values in array to text box
this.textBoxScoreOutput.Text = "Array: ";
foreach (int i in score)
{
this.textBoxScoreOutput.Text += "[" + i.ToString() + "] ";
}
int sum = score.Sum();
this.textBoxScoreOutput.Text += "The Sum of the array is: " + sum.ToString();
}
}
}
So this is checking the first two of the thirty questions and is working exactly how I need it to and thought it would.
I was wondering if I could loop just one of these "blocks" and have it check all thirty questions. I have searched and searched but can't find exactly what I am looking for (I also understand I may not be searching for the right thing either).
I am just trying to avoid having thirty of these "blocks" in my program. I feel like it would just be a mess with thirty of these. Is this possible?
Start with creating a UserControl which encapsulates the logic for a single question:
Question Text
Selected option
Once you have a single question working, you can drop any number of User Controls on to a form, configure the question text and then only have to loop through the set of user controls to get your answers. The answer would be best returned as an enumeration.
There are a number of ways to achieve this, such as code to generate the controls, or binding the selections back to a ViewModel class, but a user control is a great start.
Here's how I do it roughly:
var resultList = new List<KeyValuePair<string, int>>();
foreach (var control in this.Controls)
{
if (control is GroupBox)
{
GroupBox gb = (GroupBox)control;
foreach (Control controll in gb.Controls)
{
if (controll is RadioButton)
{
RadioButton rb = new RadioButton();
rb = (RadioButton)controll;
//rb will allow you to access all of the RadioButton's properties and act accordingly.
if (rb.Checked)
{
int score;
if (rb.Name.Contains("ButtonSD"))
score = 1;
if (rb.Name.Contains("ButtonD"))
score = 2;
//So on...
resultList.Add(new KeyValuePair<string, int>(gb.Name, score));
}
}
}
}
}
Had a rough day so maybe someone can come up with something better, but if you don't feel like reorganizing the whole thing, this might work.

Change text of a listview

I have a quick question about listView's and how check if a ListView (which contains null items) has a certain string?
Here is the code which add to sepcific items (under column 5 in the listView). It basically checks if that item appears in Google search or not. If it does, it'll write yes to that specific row, if not it'll leave it blank:
string google2 = http.get("https://www.google.com/search?q=" + textBox1.Text + "");
string[] embedid = getBetweenAll(vid, "type='text/html' href='http://www.youtube.com/watch?v=", "&feature=youtube_gdata'/>");
for (int i = 0; i < embedid.Length; i++)
{
if (google2.Contains(embedid[i]))
{
listView1.Items[i].SubItems.Add("Yes");
}
}
Now what I am trying to do is check if that certain column contains items that say Yes. If it does color them Green if not don't.
Here's the code for that:
if (i.SubItems[5].Text.Contains("Yes"))
{
labelContainsVideo.ForeColor = System.Drawing.Color.Green;
}
My issue is I keep getting an error that says InvalidArgument=Value of '5' is not valid for 'index'.
My hunch is that there are null items in column 5 which might be messing it up but I dont know.
Any idea on how to fix this?
Check the Item to see if the SubItem Collection has the correct Number of values.
i.e.
int threshold = 5;
foreach (ListViewItem item in listView1.Items)
{
if (item.SubItems.Count > threshold)
{
if (item.SubItems[5].Text.Contains("Yes"))
{
// Do your work here
}
}
}

Categories