Code for Alternating 2 Box Pattern using if statements - c#

I am trying to find a code that helps to create a pattern of:
but the number of rows and columns are custom.
Currently this is the code I have but it doesnt apply properly for all values.
(labelseat.backcolour=color.red , refers to the red boxes)
count=0;
if (Row%2==0)
{
count+=1;
if (count==3)
{
labelSeat.BackColor=Color.Red;
}
else if (count==4)
{
labelSeat.BackColor=Color.Red;
count=0;
}
}
if (Row%2==1)
{
count+=1;
if (count==1)
{
labelSeat.BackColor=Color.Red;
}
else if (count==2)
{
labelSeat.BackColor=Color.Red;
}
else if (count==4)
{
count=0;
}
}

Maybe something like this:
private void ColorBox(int elementNumber)
{
boolean colorRed = ((int)elementNumber/2) % 2 == 0;
Box[elementNumber].backgroundColor = colorWhite ? "#FF0000" : "#FFFFFF";
}

Related

C# Winforms TextBox Validation check

I have 3 pairs of textboxes in a windows form :-
TxtboxSourceFolder1 -> TxtboxDestinationFolder1
TxtboxSourceFolder2 -> TxtboxDestinationFolder2
TxtboxSourceFolder3 -> TxtboxDestinationFolder3
I am creating a List<string> SrcFolders and a List<string> DestFolders.
Now I have to validate the user input:-
1) Is there a value for TxtboxSourceFolder1, If yes, Is there a corresponding value in TxtboxDestinationFolder1 ? If all answers are yes, and the values are legitimate then add them to corresponding lists. And then repeat.
To me it seems like to check if a textbox is empty:-
private int ConstructSourceDestinationFolderList()
{
if (Directory.Exists(txtboxSrcFolder1.Text) && Directory.Exists(txtboxDestFolder1.Text))
{
trans.szSourceFolderList.Add(txtboxSrcFolder1.Text.ToString());
trans.szDestinationFolderList.Add(txtboxDestFolder1.Text);
}
else
{
return 1;
}
if (!String.IsNullOrWhiteSpace(txtboxSrcFolder2.Text))
{
if (Directory.Exists(txtboxSrcFolder2.Text) && Directory.Exists(txtboxDestFolder2.Text))
{
trans.szSourceFolderList.Add(txtboxSrcFolder2.Text);
trans.szDestinationFolderList.Add(txtboxDestFolder2.Text);
}
else
{
return 1;
}
}
if (!String.IsNullOrWhiteSpace(txtboxSrcFolder3.Text))
{
if (Directory.Exists(txtboxSrcFolder3.Text) && Directory.Exists(txtboxDestFolder3.Text))
{
trans.szSourceFolderList.Add(txtboxSrcFolder3.Text);
trans.szDestinationFolderList.Add(txtboxDestFolder3.Text);
}
else
{
return 1;
}
}
return 0;
}
Now I have to do the same thing for all of the textboxes. This seems cumbersome. Is there a more compact way to design this validation?

Check if while loop is in first iteration in C#

How Can i check if it's the first iteration in my while loop in C#?
while (myCondition)
{
if(first iteration)
{
//Do Somthin
}
//The rest of the codes
}
bool firstIteration = true;
while (myCondition)
{
if(firstIteration )
{
//Do Somthin
firstIteration = false;
}
//The rest of the codes
}
You could move the do something out of the loop. Only guaranteed to do the exact same if the "Do Somthin" does not change myCondition. And myCondition test is pure, i.e. no side effects.
if (myCondition)
{
//Do Somthin
}
while (myCondition)
{
//The rest of the codes
}
use a counter:
int index = 0;
while(myCondition)
{
if(index == 0) {
// Do something
}
index++;
}
You could make a bool outside the loop
bool isFirst = true;
while (myCondition)
{
if(isFirst)
{
isFirst = false;
//Do Somthin
}
//The rest of the codes
}
Something like this?
var first=true;
while (myCondition)
{
if(first)
{
//Do Somthin
}
//The rest of the codes
first=false
}
Define a boolean variable:
bool firstTime = true;
while (myCondition)
{
if(firstTime)
{
//Do Somthin
firstTime = false;
}
//The rest of the codes
}
You can do that by workarounds, like:
boolean first = true;
while (condition)
{
if (first) {
//your stuff
first = false;
}
}
Try something like this:
bool firstIteration = true;
while (myCondition)
{
if(firstIteration)
{
//Do Something
firstIteration = false;
}
//The rest of the codes
}
I would recommend using counter variable for this, or a for loop.
E.G.
int i = 0;
while (myCondition)
{
if(i == 0)
{
//Do Something
}
i++;
//The rest of the codes
}
Still learning, but this way came to me, have not used this before myself but I plan to test and possibly implement in my project:
int invCheck = 1;
if (invCheck > 0)
{
PathMainSouth(); //Link to somewhere
}
else
{
ContinueOtherPath(); //Link to a different path
}
static void PathMainSouth()
{
// do stuff here
}
static void ContinueOtherPath()
{
//do stuff
}

List order (or iteration) malfunction

Hello I am having trouble with an iteration through a list of 17 labels:
for (int i = 0; i < labels.Count - 1; i++)
{
MessageBox.Show(labels[i].Name);
if (labels[i].Visible == false && labels[i + 1].Visible == true)
{
...
Here are the results I get:
First it goes from label10 to label17, and then in descending order from label9 to label2.
Here is how I add the labels to the list:
private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach (Control c in this.Controls)
{
if (c is Label)
{
labels.Add(c);
c.Enabled = true;
if (c.Visible == false)
{
c.Visible = true;
}
}
}
}
I want it to go from label1 to label16, since the loop is just a loop I guess the problem lies in the order in which the labels were added to the list, but I am not sure how to fix it.
Your main problem is lexicographic order which is inherently used when you sort by Name of the label, what you want is to sort by numbers after the term label. In that case, first sort the labels list and then run the for statement over it, check the code:
var lst = labels.OrderBy(x => int.Parse(x.Name.Substring("label".Length))).ToList();
for (int i = 0; i < lst.Count - 1; i++)
{
MessageBox.Show(lst[i].Name);
...
But have in mind that this code is simple and presumes that label Name property always starts with "label" string. If that can change you must handle that case.
I guess you want to sort the labels according to their names?
labels.Sort((x, y) => { return x.Name.CompareTo(y.Name); });
but what are the difference between:
Show "Label 1" first, then "Label 2", and
Show "Label 2" first, then "Label 1"?
Check the designer.cs file to see in which order the labels are added to the Form
assuming that you have Labels id as Label1,Label2..........,Label16
in order to get the labels serially you have to write the following code
labels = labels.ConvertAll<Control>(GetIdFromLabel);
labels.Sort((x, y) => { return x.Id.CompareTo(y.Id); });
public Control GetIdFromLabel(Control c)
{
c.Id = c.Name.Replace("Label", "") == "" ? 0 : Convert.ToInt32(c.Name.Replace("Label", ""));
return c;
}
add this class in your code also
public class Control
{
public string Name { get; set; }
public int Id { get; set; }
}
Try this out:
private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
{
labels.Clear();
Control[] matches;
for (int i = 1; i <= 16; i++)
{
matches = this.Controls.Find("label" + i.ToString(), true);
if (matches.Length > 0 && matches[0] is Label)
{
Label lbl = (Label)matches[0];
labels.Add(lbl);
lbl.Enabled = true;
if (lbl.Visible == false)
{
lbl.Visible = true;
}
}
}
}

CheckBox for Windows Phone

I used 4 checkbox in my application and created an integer list to add value if the checkbox is checked. The value will be stored in my database using sqlite. This is my code :
List<int> hobid = new List<int>();
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (Convert.ToBoolean(cricket.IsChecked))
{
hobid.Add(1);
}
else if (Convert.ToBoolean(football.IsChecked))
{
hobid.Add(2);
}
else if (Convert.ToBoolean(music.IsChecked))
{
hobid.Add(3);
}
else if (Convert.ToBoolean(reading.IsChecked))
{
hobid.Add(4);
}
int rec;
string strInserthob = "Insert into User_hobbies (User_id,Hobbies_id) values (#User_id,#Hobbies_id)";
//Here insertion is done..
for (int i = 0; i < hobid.Count; i++)
{
User_hobbies txt = new User_hobbies
{
User_id = userid,
Hobbies_id = hobid[i]
};
rec = (Application.Current as App).db.Insert<User_hobbies>(txt, strInserthob);
}
}
Can you suggest me how to get the value in a list whatever checkbox is checked.
I'm assuming the button click is a 'Save' action.
In that case, you're only saving the first match due to the else if statements. The real quick and nasty way to do it is just remove the 'if else' statements and replace it with a straight if.
if (Convert.ToBoolean(cricket.IsChecked))
{
hobid.Add(1);
}
if (Convert.ToBoolean(football.IsChecked))
{
hobid.Add(2);
}
if (Convert.ToBoolean(music.IsChecked))
{
hobid.Add(3);
}
if (Convert.ToBoolean(reading.IsChecked))
{
hobid.Add(4);
}

Method to Find GridView Column Index by Name

I'm trying to write a small method to loop through and find a GridView Column by its Index, since it can change position based on what might be visible.
Here is what I have so far:
private int GetColumnIndexByName(GridView grid, string name)
{
foreach (DataColumn col in grid.Columns)
{
if (col.ColumnName.ToLower().Trim() == name.ToLower().Trim()) return col.Ordinal;
}
return -1;
}
In this case, DataColumn doesn't appear to be the right type to use, but I'm kind of lost as to what I should be doing here.
I can only use .NET 2.0 / 3.5. I can't use 4.0.
I figured it out, I needed to be using DataControlField and slightly different syntax.
The working version:
private int GetColumnIndexByName(GridView grid, string name)
{
foreach (DataControlField col in grid.Columns)
{
if (col.HeaderText.ToLower().Trim() == name.ToLower().Trim())
{
return grid.Columns.IndexOf(col);
}
}
return -1;
}
I prefer collection iteration but why bother with the overhead of foreach and grid.Columns.IndexOf call in this case? Just iterate through array with an index.
private int GetColumnIndexByName(GridView grid, string name)
{
for(int i = 0; i < grid.Columns.Count; i++)
{
if (grid.Columns[i].HeaderText.ToLower().Trim() == name.ToLower().Trim())
{
return i;
}
}
return -1;
}
Better solution which works for Datafield, SortExpression and headerText.
public static int GetBoundFieldIndexByName(this GridView gv,string name)
{
int index = 0;
bool found = false;
foreach (DataControlField c in gv.Columns)
{
if (c is BoundField)
{
BoundField field = (BoundField)c;
if (name == field.DataField ||
name == field.SortExpression ||
name == field.HeaderText)
{
found = true;
break;
}
}
index++;
}
return found ? index : -1;
}
//Get index of column by header text.
int GetColumnIndexByName(GridViewRow row, string headerText)
{
int columnIndex = 0;
foreach (DataControlFieldCell cell in row.Cells)
{
if(cell.ContainingField is TemplateField){
if(((TemplateField)cell.ContainingField).HeaderText.Equals(headerText))
{
break;
}
}
if(cell.ContainingField is BoundField){
if (((BoundField)cell.ContainingField).HeaderText.Equals(headerText))
{
break;
}
}
columnIndex++;
}
return columnIndex;
}
In case if you need a column itself and not just its index you can use some Linq magic:
DataControlField col=GridView1.Columns.Cast<DataControlField>().First(c => c.HeaderText == "Column_header")
Here's a VB version
Protected Function GetColumnIndexByHeaderText(grid As GridView, findHeader As String) As Integer
Dim i As Integer = 0
For i = 0 To grid.Columns.Count - 1
If grid.Columns(i).HeaderText.ToLower().Trim() = findHeader.ToLower().Trim() Then
Return i
End If
Next
Return -1
End Function
This way, works for me (.NET Gridview):
private int GetColumnIndexByName(GridView grid, string name)
{
for (int i = 0; i < grid.HeaderRow.Cells.Count; i++)
{
if (grid.HeaderRow.Cells[i].Text.ToLower().Trim() == name.ToLower().Trim())
{
return i;
}
}
return -1;
}

Categories

Resources