Windows Forms Button codes - c#

I am trying to create/code for a search button in C# Forms.
This what I have so far:
private void btnSearch_Click(object sender, EventArgs e)
{
for (int i = 0; i < lstCustomerDB.Items.Count; i++)
{
string item = lstCustomerDB.Items[i].ToString();
if (item.Contains(txtSearch.Text))
{
index = 1;
}
}
lstCustomerDB.Items.Clear();
if (index < 0)
{
`enter code here` MessageBox.Show("Item not found.");
txtSearch.Text = String.Empty;
}
else
{
lstCustomerDB.SelectedIndex = index;
}
}
Any help would be grateful for! Thanks!

Using LINQ:
private void Search()
{
//Grab the first item that matches (or null if not found)
var firstMatch = lstCustomerDB.Items.Cast<string>()
.FirstOrDefault(x => x.Contains(txtSearch.Text));
if (firstMatch != null)
{
lstCustomerDB.SelectedItem = firstMatch;
}
else
{
MessageBox.Show("Item not found.");
txtSearch.Text = String.Empty;
}
}
Modifying your code:
int index = -1;
for (int i = 0; i < lstCustomerDB.Items.Count; i++)
{
string item = lstCustomerDB.Items[i].ToString();
if (item.Contains(txtSearch.Text))
{
index = i;
lstCustomerDB.SelectedIndex = index;
break;
}
}
if (index < 0)
{
MessageBox.Show("Item not found.");
txtSearch.Text = String.Empty;
}

Related

Why Is This Code Running Longer Character Combinations Than Necessary?

I'm a math student with little to no experience programming, but I wrote this to act like a brute force algorithm. It seems to run fine except that it runs all the password combinations out to 3 characters for passwords as short as 2. Also I'm sure there's a way to refactor the for and if statements as well. Any help would be appreciated, thanks.
I've already been testing to see if some of the if statements aren't executing, and it looks like the statements with "console.writeln(Is this executing)" aren't executing but I'm not really sure.
public Form1()
{
InitializeComponent();
}
static char[] Match ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j' ,'k','l','m','n','o','p',
'q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','C','L','M','N','O','P',
'Q','R','S','T','U','V','X','Y','Z','!','?',' ','*','-','+'};
private string[] tempPass;
private void button1_Click(object sender, EventArgs e)
{
string tempPass1 = "lm";
string result = String.Empty;
int passLength = 1;
int maxLength = 17;
tempPass = new string[passLength];
for (int i = 0; i < Match.Length; i++)
{
if (tempPass1 != result)
{
tempPass[0] = Match[i].ToString();
result = String.Concat(tempPass);
if (passLength > 1)
{
for (int j = 0; j < Match.Length; j++)
{
if (tempPass1 != result)
{
tempPass[1] = Match[j].ToString();
result = String.Concat(tempPass);
if (passLength > 2)
{
for (int k = 0; k < Match.Length; k++)
{
if (tempPass1 != result)
{
tempPass[2] = Match[k].ToString();
result = String.Concat(tempPass);
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass[2] == "+" && tempPass1 != result)
{
Console.WriteLine("This will execute?");
passLength++;
tempPass = new string[passLength];
k = 0;
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is big gay: " + result);
break;
}
}
}
}
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass1 != result)
{
Console.WriteLine("Did this execute?");
passLength++;
tempPass = new string[passLength];
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is bigger gay: " + result);
break;
}
}
}
}
//tempPass[1] = "World!";
//Console.WriteLine(result);
if (tempPass[tempPass.Length - 1] == "+" && tempPass1 != result)
{
passLength++;
tempPass = new string[passLength];
Console.WriteLine(tempPass.Length + " " + result + " " + "Success");
Console.WriteLine(i);
i = 0; /**update
j = 0;
k = 0;
l = 0;
m = 0;*/
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is biggest gay: " + result);
}
}
}
}
Play with this; modified from my answer here. It'll show you all the 2 and 3 length combinations. Clicking the button will start/stop the generation process. You need a button, label, and a timer:
public partial class Form1 : Form
{
private Revision rev;
public Form1()
{
InitializeComponent();
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = !timer1.Enabled;
}
private void timer1_Tick(object sender, EventArgs e)
{
rev.NextRevision();
if (rev.CurrentRevision.Length == 4)
{
timer1.Stop();
MessageBox.Show("Sequence Complete");
// make it start back at the beginning?
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
else
{
label1.Text = rev.CurrentRevision;
}
}
}
public class Revision
{
private string chars;
private char[] values;
private System.Text.StringBuilder curRevision;
public Revision()
{
this.DefaultRevision();
}
public Revision(string validChars)
{
if (validChars.Length > 0)
{
chars = validChars;
values = validChars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
else
{
this.DefaultRevision();
}
}
public Revision(string validChars, string startingRevision)
: this(validChars)
{
curRevision = new System.Text.StringBuilder(startingRevision.ToUpper());
int i = 0;
for (i = 0; i <= curRevision.Length - 1; i++)
{
if (Array.IndexOf(values, curRevision[i]) == -1)
{
curRevision = new System.Text.StringBuilder(values[0]);
break;
}
}
}
private void DefaultRevision()
{
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
values = chars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
public string ValidChars
{
get { return chars; }
}
public string CurrentRevision
{
get { return curRevision.ToString(); }
}
public string NextRevision(int numRevisions = 1)
{
bool forward = (numRevisions > 0);
numRevisions = Math.Abs(numRevisions);
int i = 0;
for (i = 1; i <= numRevisions; i++)
{
if (forward)
{
this.Increment();
}
else
{
this.Decrement();
}
}
return this.CurrentRevision;
}
private void Increment()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index < (chars.Length - 1))
{
index = index + 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[0];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index < (values.Length - 1))
{
index = index + 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[0];
}
}
curRevision.Insert(0, values[0]);
}
}
private void Decrement()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[values.Length - 1];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[values.Length - 1];
}
}
curRevision.Remove(0, 1);
if (curRevision.Length == 0)
{
curRevision.Insert(0, values[0]);
}
}
}
}

How to split value in asp.net?

I Have a input value like
["Administrator","Basant Sharma"]
but i want to convert it
Administrator,Basant Sharma
using asp.net c#
CODE
protected void btnsubmit_Click(object sender, EventArgs e)
{
int val = 0;
if (textarea.Text != "")
{
string SUCode = textarea.Text; // ["Administrator","Basant Sharma"]
string[] myarray = textarea.Text.Split(',');
for (var i = 0; i < myarray.Length; i++)
{
var item = myarray[i];
// work with item here
}
for (int cnt = 0; cnt <= myarray.Length - 1; cnt++)
{
string splitComplaint = myarray[cnt];
}
}
}
That looks like JSON, and I would simply parse it as such:
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
var str = "[\"Administrator\",\"Basant Sharma\"]";
var items = JsonConvert.DeserializeObject<string[]>(str);
foreach (var item in items) {
Console.WriteLine("Item: {0}", item);
}
}
}
.NET Fiddle here: https://dotnetfiddle.net/i3M8yp
This is a very naive way of doing it, but will do the trick:
protected void btnsubmit_Click(object sender, EventArgs e)
{
int val = 0;
if (textarea.Text != "")
{
string SUCode = textarea.Text;
SUCode = SUCode.Replace("\"","").Replace("[","").Replace("]","");
string[] myarray = SUCode.Split(',');
SUCode = "";
for (var i = 0; i < myarray.Length; i++)
{
SUCode += myarray[i];
if(i < myarray.Length-1)
SUCode += ",";
}
}
}
Just Loop through and replace values like below
string text = "[Administrator\",\"Basant Sharma\"]";
string result = string.Empty;
var words = text.Split(',');
for (int i = 0; i < words.Length; i++)
{
words[i] = words[i].Replace("\"", "");
words[i] = words[i].Replace("[", "");
words[i] = words[i].Replace("]", "");
if ( i == words.Length - 1)
{
result += words[i];
}
else
{
result += words[i] + ",";
}
}
Console.WriteLine(result);
Output : Administrator,Basant Sharma

How can I select and Deselect all items by checkbox in dynamically added check _list_box in c#?

I wanted to do select/ deselect with one checkbox. I have tried to get the index of the selected item. I haven't been able to get this, so I tried to change the name of the box. Still no success.
foreach (var item in DATAsetname_INIlist)
{
checkedListBox2.Items.Add(item);
}
if (checkedListBox2.Items.Count != 0)
{
checkedListBox2.Items.Add("Select all");
}
private void checkedListBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (checkedListBox2.Items.Count != 0)
{
if (checkedListBox2.SelectedItem.ToString() == "Select all")
{
for (int i = 0; i < checkedListBox2.Items.Count; i++)
{
checkedListBox2.SetItemChecked(i, true);
}
string changed = "Deselect all";
checkedListBox2.SelectedItem =changed;
}
if (checkedListBox2.SelectedItem.ToString() == "Deselect all")
{
for (int i = 0; i < checkedListBox2.Items.Count; i++)
{
checkedListBox2.SetItemChecked(i, false);
}
string changed = "Select all";
checkedListBox2.SelectedItem = changed;
}
}
}
can you please help on this ? thank you
Have done quick exercise. Please modify your code accordingly.
/// <summary>
/// Check all check boxes and vice versa
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ChkSelectAll_CheckedChanged(object sender, EventArgs e)
{
//Declare your checkedListBox2 count
iCount = checkedListBox2.Items.Count;
if (sender != null)
{
for (int i = 1; i <= iCount; i++)
{
CheckBox ck = null;
Control[] chkTest = this.Controls.Find("chkDrive" + i, true);
if (chkTest.Length > 0)
{
if (chkSelectAll.Checked)
{
for (int j = 0; j < chkTest.Length; j++)
{
ck = (CheckBox)chkTest[j];
ck.Checked = true;
}
}
else
{
for (int j = 0; j < chkTest.Length; j++)
{
ck = (CheckBox)chkTest[j];
ck.Checked = false;
}
}
}
}
}
}
can you try this.
try
{
checkedListBox1.SelectedIndexChanged -= checkedListBox1_SelectedIndexChanged;
if (checkedListBox1.Items.Count != 0)
{
if (checkedListBox1.SelectedItem.ToString() == "Select all")
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
checkedListBox1.SetItemChecked(i, true);
}
string changed = "Deselect all";
checkedListBox1.Items[checkedListBox1.SelectedIndex] = changed;
}
else if (checkedListBox1.SelectedItem.ToString() == "Deselect all")
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
checkedListBox1.SetItemChecked(i, false);
}
string changed = "Select all";
checkedListBox1.Items[checkedListBox1.SelectedIndex] = changed;
}
}
}
catch (Exception ex)
{
}
finally
{
checkedListBox1.SelectedIndexChanged += checkedListBox1_SelectedIndexChanged;
}
If this is C# based, windows application.
Search form collection and find all check box on form, using for each.
Code
foreach(CheckBox item in Form.Control)
{
Item.Checked=true;
}
For check list box
for(int i;I<checklistbox.items.count;I++)
{
checklistbox.SetItemChecked(I,true);
}
When i work with c# i had litle simillar problem in my case was enought was to replace if(string==string) by string.equals(string)
Btw few questions:
checkedListBox2.SelectedItem.ToString() what is value in here where comparing?
Does your listener work at all?
Not better way to check which checkBox is taken comparing sender in switch?
How u declare checkedListBox2
By checkedListBox2.Items.Add(item); i suspect u create checkBoxes by hand can u show it? meybe something is there wrong
This part added after Lian comment
foreach(var item in DATAsetname_INIlist)
{
checkedListBox2.Items.Add(item);
}
if (checkedListBox2.Items.Count != 0) {
checkedListBox2.Items.Add("Select all");
}
private void checkedListBox2_SelectedIndexChanged (object sender, EventArgs e)
{
if (checkedListBox2.Items.Count != 0 && checkedListBox2.SelectedItem.ToString().equals("Select all")) {
changeStateOfSelectedItem("Deselect all", true);
} else if (checkedListBox2.SelectedItem.ToString().equals("Deselect all")) {
changeStateOfSelectedItem("Select all", false);
}
}
private void changeStateOfSelectedItem (String state, bolean stateToReplace){
for (int i = 0; i < checkedListBox2.Items.Count; i++) {
checkedListBox2.SetItemChecked(i, stateToReplace);
}
string changed = state;
checkedListBox2.SelectedItem = changed;

how i do create find similar excel?

i want create search in form similar EXCEL , find and put (row) in listview
this my form :
and my code :
private int searchIndex = -1;
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Find Next";
try
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
searchIndex = (searchIndex + 1) % dataGridView1.Rows.Count;
DataGridViewRow row = dataGridView1.Rows[searchIndex];
if (row.Cells["Product"].Value == null)
{
continue;
}
if (row.Cells["Product"].Value.ToString().Trim().StartsWith(textBox1.Text) || row.Cells["Product"].Value.ToString().Trim().Contains(textBox1.Text))
{
ListViewItem lvi = new ListViewItem(row.Cells["Product"].Value.ToString());
lvi.SubItems.Add(row.Cells["Product"].Value.ToString());
listView1.Items.Add(lvi);
dataGridView1.CurrentCell = row.Cells["Product"];
dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows[row.Index].Index;
row = dataGridView1.Rows[i];
return;
}
}
}
catch { }
}
and in textbox1_textchanged :
searchIndex = -1;
button1.Text = "Find";
listView1.Clear();
I want when search end, send message ...
thanks
Mimicking the Find All functionality, populating your ListView will be very similar to the Find Next functionality. Here's an example if it were a separate button from Find Next:
public Form1()
{
InitializeComponent();
listView1.View = View.Details;
listView1.Columns.Add("Column");
listView1.Columns.Add("Row");
listView1.Columns.Add("Value");
}
private void button2_Click(object sender, EventArgs e)
{
button2.Text = "Find All";
int tempIndex = -1;
listView1.Items.Clear();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
tempIndex = (tempIndex + 1) % dataGridView1.Rows.Count;
DataGridViewRow row = dataGridView1.Rows[tempIndex];
if (row.Cells["Foo"].Value == null)
{
continue;
}
if (row.Cells["Foo"].Value.ToString().Trim().StartsWith(textBox1.Text) || row.Cells["Foo"].Value.ToString().Trim().Contains(textBox1.Text))
{
DataGridViewCell cell = row.Cells["Foo"];
ListViewItem lvRow = new ListViewItem(new string[] { cell.ColumnIndex.ToString(), cell.RowIndex.ToString(), cell.Value.ToString() });
listView1.Items.Add(lvRow);
}
}
MessageBox.Show("Search ended."); // Or whatever message you intend to send.
}

Analogy between list_view_SelectedIndexChanged and list_box_SelectedIndexChanged

I have a handler for list_box:
private void list_answers_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < tasks.Count; i++)
{
if (list_answers.Text == "Question №" + (i + 1))
{
this.ShowOnePanel(i);
iter = i;
break;
}
}
}
and for list_view:
private void list_answers_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < tasks.Count; i++)
{
if (list_answers.Items[i].Text == "Question №" + (i + 1))
{
this.ShowOnePanel(i);
iter = i;
break;
}
}
}
It works for listbox, but doesn't work for listview. Why?
P.S. ShowOnePanel is my method, that shows one of the panels with question.
if (list_answers.Items[i].Text == "Питання №" + (i + 1))
I guess it's "question" not "Питання"
EDIT
private void list_answers_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < tasks.Count; i++)
{
if (list_answers.Items[i].Selected == true) // find selected item
{
if (list_answers.Items[i].Text == "Question №" + (i + 1)) // check it's content
this.ShowOnePanel(i);
iter = i;
break;
}
}
}

Categories