Check if textbox has same value to other textbox - c#

I want to check if there are similar value in my textboxes, I have 10 Textboxes, and on button click I want to validate if there are the same vales
for (int c = 1; c <= 10; c++)
{
TextBox check_subjName = table_textboxes.FindControl("subject_name" + c.ToString()) as TextBox;
for (int b = 1; b <= 10; b++)
{
TextBox check_subjName2 = table_textboxes.FindControl("subject_name" + b.ToString()) as TextBox;
if (c != b)
{
if (check_subjName.Text == check_subjName2.Text)
{
//there are similar values
}
}
}
}

So it is valid if all textboxes have different values. You could use LINQ:
List<string> textList = table_textboxes.Controls.OfType<TextBox>()
.Where(txt => txt.ID.StartsWith("subject_name"))
.Select(txt => txt.Text.Trim())
.ToList();
var distinctTexts = new HashSet<string>(textList);
bool allDifferent = textList.Count == distinctTexts.Count;
here a slightly optimized approach (in this case micro optimization):
var textList = table_textboxes.Controls.OfType<TextBox>()
.Where(txt => txt.ID.StartsWith("subject_name"))
.Select(txt => txt.Text.Trim());
HashSet<string> set = new HashSet<string>();
bool allDifferent = textList.All(set.Add);

Related

How to count checked checkbox values in C#

I'm new to C# and trying to learn a few things. For example, I can't get the process beneath together. What am I doing wrong?
The issue I get is that when all 4 checkboxes are selected I only get 5 as result as they are all 5 selected...? and must be 20 (4x5)
//CheckCheckedCheckboxes
int Totalchecked = 0;
if (CheckBox1.Checked)
{
Totalchecked = 5;
}
if (CheckBox2.Checked)
{
Totalchecked = 5;
}
if (CheckBox3.Checked)
{
Totalchecked = 5;
}
if (CheckBox4.Checked)
{
Totalchecked = 5;
}
var totalselected = Totalchecked ;
labelHeader.Text = Convert.ToString(totalselected);
private void button1_Click(object sender, EventArgs e)
{
int Totalchecked = 0;
int TotalValue = 0;
foreach (Control item in this.Controls)
{
if(item is CheckBox)
{
if (((CheckBox)item).Checked)
Totalchecked++;
}
}
//If you consider, each check box value as a 5, just multiply Totalchecked * 5
TotalValue = Totalchecked * 5;
MessageBox.Show(TotalValue.ToString());
}
But the above approach is not good when forms contain more than these checkboxes, So just add your checkboxes into the Group box and, you can get a count of the checked checkboxes as follows,
int Totalchecked = groupBox1.Controls.OfType<CheckBox>().Where(c => c.Checked).Count();
Updated: Based on your comment, you can set Tag value for a each Check box as,
checkBox1.Tag = 5;
checkBox2.Tag = 10;
int totalValueOfeachCheckboxes = 0;
foreach (Control item in this.Controls)
{
if(item is CheckBox)
{
if (((CheckBox)item).Checked)
{
totalValueOfeachCheckboxes = totalValueOfeachCheckboxes + Convert.ToInt32(item.Tag);
}
}
}
MessageBox.Show(totalValueOfeachCheckboxes.ToString());
You can loop over them and iterate on the controls on the form.
foreach(Control c in this.Controls)
{
if(c is CheckBox)
{
// Do stuff here/logic
}
}
Or do a more LINQ/Lamba-ish type approach of
var checkList = YourForm.Controls.OfType<CheckBox>().Where(x => x.Checked).ToList();
checkList.ForEach(x => {
//Do stuff here
});

CheckBoxList In GridView Only Remember The First Option Ticked When New Row Added

I have a grid view with multiple columns which allow user to fill in the data and they are able to add a new row after finishing filling the data. Among the columns, there is a column with CheckBoxList which I allow user to multiple select the option on the CheckBoxList but every time add a new row, only the first option select by the user is remain while other selection is gone. How am I able to let the option selected by the user remain while I add a new row?
private void SetPreviousDataLecturer()
{
int rowIndex = 0;
if (ViewState["LecturerGridView"] != null)
{
DataTable dataTableCurrent = (DataTable)ViewState["LecturerGridView"];
if (dataTableCurrent.Rows.Count > 0)
{
for (int i = 0; i < dataTableCurrent.Rows.Count; i++)
{
TextBox textBoxLName = (TextBox)LecturerGridView.Rows[rowIndex].Cells[1].FindControl("LecturerName");
TextBox textBoxLID = (TextBox)LecturerGridView.Rows[rowIndex].Cells[2].FindControl("LecturerID");
TextBox textBoxLAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[3].FindControl("LecturerAddress");
TextBox textBoxLPNumber = (TextBox)LecturerGridView.Rows[rowIndex].Cells[4].FindControl("LecturerPNumber");
TextBox textBoxLEAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[5].FindControl("LecturerEAddress");
CheckBoxList checkBoxListLCourse = (CheckBoxList)LecturerGridView.Rows[rowIndex].Cells[6].FindControl("LecturerCourse");
TextBox textBoxLPassword = (TextBox)LecturerGridView.Rows[rowIndex].Cells[7].FindControl("LecturerPassword");
LecturerGridView.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
textBoxLName.Text = dataTableCurrent.Rows[i]["LecturerName"].ToString();
textBoxLID.Text = dataTableCurrent.Rows[i]["LecturerID"].ToString();
textBoxLAdd.Text = dataTableCurrent.Rows[i]["LecturerAddress"].ToString();
textBoxLPNumber.Text = dataTableCurrent.Rows[i]["LecturerPNumber"].ToString();
textBoxLEAdd.Text = dataTableCurrent.Rows[i]["LecturerEAddress"].ToString();
checkBoxListLCourse.SelectedValue = dataTableCurrent.Rows[i]["LecturerCourse"].ToString();
textBoxLPassword.Text = dataTableCurrent.Rows[i]["LecturerPassword"].ToString();
rowIndex++;
}
}
}
}
private void AddNewRowToLecturerGV()
{
int rowIndex = 0;
if (ViewState["LecturerGridView"] != null)
{
DataTable dataTableCurrent = (DataTable)ViewState["LecturerGridView"];
DataRow dataRowCurrent = null;
if (dataTableCurrent.Rows.Count > 0)
{
for (int i = 1; i <= dataTableCurrent.Rows.Count; i++)
{
TextBox textBoxLName = (TextBox)LecturerGridView.Rows[rowIndex].Cells[1].FindControl("LecturerName");
TextBox textBoxLID = (TextBox)LecturerGridView.Rows[rowIndex].Cells[2].FindControl("LecturerID");
TextBox textBoxLAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[3].FindControl("LecturerAddress");
TextBox textBoxLPNumber = (TextBox)LecturerGridView.Rows[rowIndex].Cells[4].FindControl("LecturerPNumber");
TextBox textBoxLEAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[5].FindControl("LecturerEAddress");
CheckBoxList checkBoxListLCourse = (CheckBoxList)LecturerGridView.Rows[rowIndex].Cells[6].FindControl("LecturerCourse");
TextBox textBoxLPassword = (TextBox)LecturerGridView.Rows[rowIndex].Cells[7].FindControl("LecturerPassword");
dataRowCurrent = dataTableCurrent.NewRow();
dataRowCurrent["RowNumber"] = i + 1;
dataTableCurrent.Rows[i - 1]["LecturerName"] = textBoxLName.Text;
dataTableCurrent.Rows[i - 1]["LecturerID"] = textBoxLID.Text;
dataTableCurrent.Rows[i - 1]["LecturerAddress"] = textBoxLAdd.Text;
dataTableCurrent.Rows[i - 1]["LecturerPNumber"] = textBoxLPNumber.Text;
dataTableCurrent.Rows[i - 1]["LecturerEAddress"] = textBoxLEAdd.Text;
dataTableCurrent.Rows[i - 1]["LecturerCourse"] = checkBoxListLCourse.SelectedValue.ToString();
dataTableCurrent.Rows[i - 1]["LecturerPassword"] = textBoxLPassword.Text;
rowIndex++;
}
dataTableCurrent.Rows.Add(dataRowCurrent);
ViewState["LecturerGridView"] = dataTableCurrent;
LecturerGridView.DataSource = dataTableCurrent;
LecturerGridView.DataBind();
}
}
else
{
Response.Write("ViewState is null.");
}
SetPreviousDataLecturer();
}
You need to maintain state for selected checkbox. On the button click 'Add new row' first get the state of each rows in a DataTable and add a blank row then populate that DataTable.
You need to maintain checkbox's selected item's state also. You can get selected values in a CSV as :
string selectedItems = String.Join(",",
checkBoxListLCourse.Items.OfType<ListItem>().Where(r => r.Selected)
.Select(r => r.Value));
and you can restore as :
string[] items = selectedItems.Split(',');
for (int i = 0; i < checkBoxListLCourse.Items.Count; i++)
{
if (items.Contains(checkBoxListLCourse.Items[i].Value))
{
checkBoxListLCourse.Items[i].Selected = true;
}
}
My answer. This answer has some problem like the checkbox list will automatically scroll to the most top when we tick on anything in the checkbox list.
private void SetPreviousDataLecturer()
{
int rowIndex = 0;
if (ViewState["LecturerGridView"] != null)
{
DataTable dataTableCurrent = (DataTable)ViewState["LecturerGridView"];
if (dataTableCurrent.Rows.Count > 0)
{
for (int i = 0; i < dataTableCurrent.Rows.Count; i++)
{
TextBox textBoxLName = (TextBox)LecturerGridView.Rows[rowIndex].Cells[1].FindControl("LecturerName");
TextBox textBoxLID = (TextBox)LecturerGridView.Rows[rowIndex].Cells[2].FindControl("LecturerID");
TextBox textBoxLAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[3].FindControl("LecturerAddress");
TextBox textBoxLPNumber = (TextBox)LecturerGridView.Rows[rowIndex].Cells[4].FindControl("LecturerPNumber");
TextBox textBoxLEAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[5].FindControl("LecturerEAddress");
CheckBoxList checkBoxListLCourse = (CheckBoxList)LecturerGridView.Rows[rowIndex].Cells[6].FindControl("LecturerCourse");
TextBox textBoxLPassword = (TextBox)LecturerGridView.Rows[rowIndex].Cells[7].FindControl("LecturerPassword");
LecturerGridView.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
textBoxLName.Text = dataTableCurrent.Rows[i]["LecturerName"].ToString();
textBoxLID.Text = dataTableCurrent.Rows[i]["LecturerID"].ToString();
textBoxLAdd.Text = dataTableCurrent.Rows[i]["LecturerAddress"].ToString();
textBoxLPNumber.Text = dataTableCurrent.Rows[i]["LecturerPNumber"].ToString();
textBoxLEAdd.Text = dataTableCurrent.Rows[i]["LecturerEAddress"].ToString();
checkBoxListLCourse.Text = dataTableCurrent.Rows[i]["LecturerCourse"].ToString();
string lecturerCourse = dataTableCurrent.Rows[i]["LecturerCourse"].ToString();
if (!string.IsNullOrEmpty(lecturerCourse))
{
for (int j = 0; j < lecturerCourse.Split(',').Length; j++)
{
checkBoxListLCourse.Items.FindByValue(lecturerCourse.Split(',')[j].ToString()).Selected = true;
}
}
textBoxLPassword.Text = dataTableCurrent.Rows[i]["LecturerPassword"].ToString();
rowIndex++;
}
}
}
}
private void AddNewRowToLecturerGV()
{
int rowIndex = 0;
if (ViewState["LecturerGridView"] != null)
{
DataTable dataTableCurrent = (DataTable)ViewState["LecturerGridView"];
DataRow dataRowCurrent = null;
if (dataTableCurrent.Rows.Count > 0)
{
for (int i = 1; i <= dataTableCurrent.Rows.Count; i++)
{
TextBox textBoxLName = (TextBox)LecturerGridView.Rows[rowIndex].Cells[1].FindControl("LecturerName");
TextBox textBoxLID = (TextBox)LecturerGridView.Rows[rowIndex].Cells[2].FindControl("LecturerID");
TextBox textBoxLAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[3].FindControl("LecturerAddress");
TextBox textBoxLPNumber = (TextBox)LecturerGridView.Rows[rowIndex].Cells[4].FindControl("LecturerPNumber");
TextBox textBoxLEAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[5].FindControl("LecturerEAddress");
CheckBoxList checkBoxListLCourse = (CheckBoxList)LecturerGridView.Rows[rowIndex].Cells[6].FindControl("LecturerCourse");
TextBox textBoxLPassword = (TextBox)LecturerGridView.Rows[rowIndex].Cells[7].FindControl("LecturerPassword");
dataRowCurrent = dataTableCurrent.NewRow();
dataRowCurrent["RowNumber"] = i + 1;
dataTableCurrent.Rows[i - 1]["LecturerName"] = textBoxLName.Text;
dataTableCurrent.Rows[i - 1]["LecturerID"] = textBoxLID.Text;
dataTableCurrent.Rows[i - 1]["LecturerAddress"] = textBoxLAdd.Text;
dataTableCurrent.Rows[i - 1]["LecturerPNumber"] = textBoxLPNumber.Text;
dataTableCurrent.Rows[i - 1]["LecturerEAddress"] = textBoxLEAdd.Text;
string lecturerCourse = string.Empty;
foreach (ListItem item in checkBoxListLCourse.Items)
{
if (item.Selected)
{
if (!string.IsNullOrEmpty(lecturerCourse))
{
lecturerCourse += ",";
}
lecturerCourse += item.Value;
}
}
dataTableCurrent.Rows[i - 1]["LecturerCourse"] = lecturerCourse;
dataTableCurrent.Rows[i - 1]["LecturerPassword"] = textBoxLPassword.Text;
rowIndex++;
}
dataTableCurrent.Rows.Add(dataRowCurrent);
ViewState["LecturerGridView"] = dataTableCurrent;
LecturerGridView.DataSource = dataTableCurrent;
LecturerGridView.DataBind();
}
}
else
{
Response.Write("ViewState is null.");
}
SetPreviousDataLecturer();
}

how to save data from dynamic textbox?

this code creates a textbox dynamically based on the total number of items in a listview. my problem is how can i access these textboxes so i can save the contents of the textbox to my database?
int f = 24;
int j = 25;
for (int gg = 0; gg < listView1.Items.Count;gg++ )
{
j = f + j;
TextBox txtb = new TextBox();
txtb.Name = "tboxl1"+gg;
txtb.Location = new Point(330,j);
txtb.Visible = true;
txtb.Enabled = true;
txtb.Font = new Font(txtb.Font.FontFamily,12);
groupBox2.Controls.Add(txtb);
}
I'd be more inclined to write you code like this:
var f = 24;
var j = 25;
var textBoxes =
Enumerable
.Range(0, listView1.Items.Count)
.Select(gg =>
{
j = f + j;
var txtb = new TextBox();
txtb.Name = String.Format("tboxl1{0}", gg);
txtb.Location = new Point(330, j);
txtb.Visible = true;
txtb.Enabled = true;
txtb.Font = new Font(txtb.Font.FontFamily, 12);
return txtb;
})
.ToList();
textBoxes.ForEach(txtb => groupBox2.Controls.Add(txtb));
Now you have a variable textBoxes that saves references to the new text boxes. You can use that to get the values from the text boxes to save them to your database.
If you want all TextBox controls then:
foreach (Control control in groupBox2.Controls)
{
if (control is TextBox)
{
string value = (control as TextBox).Text;
// Save your value here...
}
}
But if you want a specific TextBox, you can get it by its name like this:
Control control = groupBox1.Controls.Find("textBox1", false).FirstOrDefault(); // returns null if no control with this name exists
TextBox textBoxControl = control as TextBox; // if you want TextBox control
string value = control.Text;
// Now you can save your value anywhere
You can get the reference to text box as follows,
Control GetControlByName(string Name)
{
foreach(Control c in this.Controls)
if(c.Name == Name)
return c;
return null;
}

Writing to Excel cells while releasing all COM objects

I am following this posts advice and trying to release all of my COM objects, including all Ranges while writing a List of string tuples to an Excel spreadsheet (using his ComObjectManager class).
I have the solution below which works, but looks like is not stacking the Range COM objects introduced by the
cells[j, column] = strings[i].Item1;
(et al) in the ComObjectManager object and therefore not releasing them. I have the commented out solution which would release the objects but I must not be understanding the syntax correctly to set the cells because it will not compile. I have also tried using
var roomNameCell = com.Get<object>(() => cells[j, column]);
for roomNameCell and areaCell, but this results in nothing being written to the cell.
I have researched the MSDN guides but can't figure out how to do this, please help.
internal void InsertStrings(List<Tuple<string, string>> strings, Excel.Range selection, ComObjectManager com)
{
const int singleRowCell = 1;
const int columnsToArea = 2;
int firstRow = selection.Row;
int column = selection.Column;
for (int i = 0, j = firstRow; i < strings.Count; )
{
selection = com.Get<Excel.Range>(() => app.Cells[j, column]);
var mergeArea = com.Get<Excel.Range>(() => selection.MergeArea);
var mergeAreaRows = com.Get<Excel.Range>(() => mergeArea.Rows);
var cells = com.Get<Excel.Range>(() => app.Cells);
if (selection.MergeCells && mergeAreaRows.Count > singleRowCell)
{
//var roomNameCell = com.Get<Excel.Range>(() => cells[j, column]);
//var areaCell = com.Get<Excel.Range>(() => cells[j, column + columnsToArea]);
//doesn't compile - cannont explicity convert from string to Range
//roomNameCell = strings[i].Item1;
//areaCell = strings[i].Item2;
//works but the Range COM objects aren't being disposed?
cells[j, column] = strings[i].Item1;
cells[j, column + columnsToArea] = strings[i].Item2;
++i;
}
j += mergeAreaRows.Count;
}
}
I figured it out, I just needed to set the Values property like this:
internal void InsertStrings(List<Tuple<string, string>> strings, Excel.Range selection, ComObjectManager com)
{
const int singleRowCell = 1;
const int columnsToArea = 2;
int firstRow = selection.Row;
int column = selection.Column;
for (int i = 0, j = firstRow; i < strings.Count; )
{
selection = com.Get<Excel.Range>(() => app.Cells[j, column]);
var mergeArea = com.Get<Excel.Range>(() => selection.MergeArea);
var mergeAreaRows = com.Get<Excel.Range>(() => mergeArea.Rows);
var cells = com.Get<Excel.Range>(() => app.Cells);
if (selection.MergeCells && mergeAreaRows.Count > singleRowCell)
{
var roomNameCell = com.Get<Excel.Range>(() => cells[j, column]);
var areaCell = com.Get<Excel.Range>(() => cells[j, column + columnsToArea]);
roomNameCell.Value = strings[i].Item1;
areaCell.Value = strings[i].Item2;
++i;
}
j += mergeAreaRows.Count;
}
}

How to access multiple buttons or textbox or any control?

I want to access multiple textbox name textbox1,textbox2,textbox3, etc.. by loop not by individual name. For that reason I created one function which create this var names.
public string[] nameCre(string cntrlName, int size)
{
string[] t = new string[size];
for (int i = 0; i < size; i++)
{
t[i] = cntrlName.ToString() + (i + 1);
}
return t;
}
for nameCre("Textbox",5); So this,function successfully returning me TextBox1, TextBox2 ... TextBox5.
But when I am trying to convert this string to TextBox control by
string[] t = new string[50];
t= nameCre("TextBox",5);
foreach (string s in t)
{
((TextBox) s).Text = "";
}
it giving me error :
Cannot convert type 'string' to 'System.Windows.Forms.TextBox'....
How can I accomplish this job?
var t = nameCre("TextBox",5);
foreach (var s in t)
{
var textBox = new TextBox {Name = s, Text = ""};
}
string[] t= new string[50];
t= nameCre("TextBox",5);
foreach (string s in t){
TextBox tb = (TextBox)this.Controls.FindControl(s);
tb.Text = "";
}
if you have many text boxes
foreach (Control c in this.Controls)
{
if (c.GetType().ToString() == "System.Windows.Form.Textbox")
{
c.Text = "";
}
}
Perhaps you need this -
string[] t = new string[50];
t = nameCre("TextBox", 5);
foreach (string s in t)
{
if (!string.IsNullOrEmpty(s))
{
Control ctrl = this.Controls.Find(s, true).FirstOrDefault();
if (ctrl != null && ctrl is TextBox)
{
TextBox tb = ctrl as TextBox;
tb.Text = "";
}
}
}
This post is quite old, anyway I think I can give you (or anyone else with a problem like that) an answer:
I think using an Array (or List) of TextBoxs would be the best solution for doing that:
// using an Array:
TextBox[] textBox = new TextBox[5];
textBox[0] = new TextBox() { Location = new Point(), /* etc */};
// or
textBox[0] = TextBox0; // if you already have a TextBox named TextBox0
// loop it:
for (int i = 0; i < textBox.Length; i++)
{
textBox[i].Text = "";
}
// using a List: (you need to reference System.Collections.Generic)
List<TextBox> textBox = new List<TextBox>();
textBox.Add(new TextBox() { Name = "", /* etc */});
// or
textBox.Add(TextBox0); // if you already have a TextBox named TextBox0
// loop it:
for (int i = 0; i < textBox.Count; i++)
{
textBox[i].Text = "";
}
I hope this helps :)

Categories