I want my label2.Text to display each concecutive result of the multiplication table, but only the last result gets displayed.
I made that each checkbox equals only one math table. checkbox1 = multiplication table 1, checkbox2 = multiplication table 2 and so on...
Why is only the last result being displayed in my label2.Text property in my Windows Form?
P.S. I am working through an introduction course of C#.
int multiplyWith;
int multiplyNumber;
for (multiplyNumber = 1; multiplyNumber <= 12; multiplyNumber++)
{
if (checkBox1.Checked == true)
{
multiplyWith = 1;
int sum = multiplyNumber * multiplyWith;
label2.Visible = true;
label2.Text = sum + "\n";
}
else if (checkBox2.Checked == true)
{
multiplyWith = 2;
int sum = multiplyNumber * multiplyWith;
label2.Visible = true;
label2.Text = sum + "\n";
}
}
You are not concatenating the result but only setting the current value.
This would work but is not the most clean/efficient way to do it:
label2.Text += sum + "\n";
Try using a StringBuilder to generate the result first and at the end assign the text box the StringBuilder value.
StringBuilder sum = new StringBuilder();
int multiplyWith = checkBox1.Checked ? 1 : 2;
for (int multiplyNumber = 1; multiplyNumber <= 12; multiplyNumber++)
{
sum.AppendLine(multiplyNumber * multiplyWith);
}
label2.Visible = true;
label2.Text = sum.ToString();
If you want you could change it to something like:
int multiplyWith;
int multiplyNumber;
var results = string.Empty;
for (multiplyNumber = 1; multiplyNumber <= 12; multiplyNumber++)
{
if (checkBox1.Checked == true)
{
multiplyWith = 1;
int sum = multiplyNumber * multiplyWith;
label2.Visible = true;
results += sum + "\n"
}
else if (checkBox2.Checked == true)
{
multiplyWith = 2;
int sum = multiplyNumber * multiplyWith;
label2.Visible = true;
results += sum + "\n"
}
}
Then after your loop exits:
label2.Text = results;
you could just edit this line from
label2.Text = sum + "\n";
to
label2.Text += sum + "\n";
Related
I am trying to display points from 7 files. Each file corresponds to a day, and I am trying to add a button where it takes the last 7 created files and displays them as x=dateTime and y= value. what this code currently does is that only displays the x axis on the left and right side.
private void button1_Click(object sender, EventArgs e)
{
chart1.Titles.Clear();
chart1.Series.Clear();
xAxis.Clear();
yAxis.Clear();
var Series1 = new Series
{
Name = comboBox2.Text,
Color = System.Drawing.Color.Green,
IsVisibleInLegend = false,
IsXValueIndexed = true,
ChartType = SeriesChartType.Area
};
this.chart1.Series.Add(Series1);
double measur = 0;
//clear graph
string Folder = #"\\Engineer\DI-808\outlooktest\";
var files = new DirectoryInfo(Folder).GetFiles("*_*");
string latestfile = "";
DateTime lastModified = DateTime.MinValue;
List<string> filesD = new List<string>();
DateTime endDate=DateTime.Now;
DateTime startDate= DateTime.Now.AddDays(-3);
DateTime dateToCheck;
Console.WriteLine(startDate + " " + endDate);
foreach (FileInfo file in files)
{
//Console.WriteLine(file.Name+"before");
string edited = file.Name.Remove(0, 6);
//Console.WriteLine(edited+"during");
char[] csv = { '.', 'c', 's', 'v'};
edited = edited.TrimEnd(csv);
//Console.WriteLine(edited + "after CSV");
edited = edited.Remove(10, 9);
// Console.WriteLine(edited+"after");
dateToCheck = Convert.ToDateTime(edited);
Console.WriteLine(dateToCheck+" date to check");
Console.WriteLine(startDate+" start");
Console.WriteLine(endDate+ " end" );
// if ( DateTime.Compare(dateToCheck,startDate)>=0dateToCheck >= startDate && dateToCheck <= endDate);
if (DateTime.Compare(dateToCheck, startDate)>=0 && DateTime.Compare(dateToCheck, endDate)<=0)
{
latestfile = file.Name;
filesD.Add(latestfile);
Console.WriteLine(latestfile+" dweeb");
}
}
Console.WriteLine(filesD.Count());
for (int i = 0; i < filesD.Count(); i++)
Console.WriteLine(files[i]);
string lineData;
try
{
for (int i=0;i<filesD.Count();i++) {
readData = new StreamReader(#"\\egvfps1.egv.mapes.local\Engineer\DI-808\outlooktest\" + filesD[i]);
for (int k = 0; k < 21; k++)
readData.ReadLine();
while ((lineData = readData.ReadLine()) != null)
{
if (Convert.ToDouble(lineData.Split(',')[comboBox2.SelectedIndex + 2]) <= 0.001)
measur = 0;
else
{
measur = Convert.ToDouble(lineData.Split(',')[comboBox2.SelectedIndex + 2]) * 110;
xAxis.Add(Convert.ToDateTime(lineData.Split(',')[1]));
yAxis.Add(measur);
}
}
}
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
readData.Close();
this.chart1.ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm:ss";
this.chart1.Titles.Add(comboBox2.Text + "(" + xAxis[0].ToString("MM/dd/yyyy") + ")");
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Hours;
chart1.ChartAreas[0].AxisX.Interval = 1;
// chart1.ChartAreas[0].AxisX.MajorGrd.Enabled = false;
//chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
chart1.ChartAreas.FirstOrDefault().AxisX.Interval = 1;
// chart1.ChartAreas.FirstOrDefault().AxisY.Interval = 1;
for (int i = 0; i < xAxis.Count(); i++)
{
chart1.Series[comboBox2.Text].Points.AddXY(xAxis[i], yAxis[i]);
}
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Hours;
chart1.ChartAreas[0].AxisX.Interval = 1;
// chart1.ChartAreas[0].AxisX.MajorGrd.Enabled = false;
//chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
chart1.ChartAreas.FirstOrDefault().AxisX.Interval = 1;
// chart1.ChartAreas.FirstOrDefault().AxisY.Interval = 1;
chart1.ChartAreas[0].AxisX.Interval = 1;
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Hours;
chart1.ChartAreas[0].AxisX.IntervalOffset = 1;
chart1.Series[0].XValueType = ChartValueType.DateTime;
}
enter image description here
I know its somewhere in the Xaxis interval type part,but I don't know what values to put in.
Any suggestions helps!
I have many if and else statements and I am wondering how I can make it short and sweet. This function checks if the answer the user input into the textbox is the same as the answer in the (hidden) datagrid. If it is the same add 1 to correctAnswer - which calculates how many correct answers the user has correct (vice versa for wrong answer)
bool firstAnswerCorrect = CheckAnswer(dataGridView1.Rows[0], textBoxQ1);
if (firstAnswerCorrect == true)
{
label1.Text = "correct";
correctAnswers = correctAnswers + 1;
}
else
{
label1.Text = "incorrect";
wrongAnswers = wrongAnswers + 1;
}
bool secondAnswerCorrect = CheckAnswer(dataGridView1.Rows[1], textBoxQ2);
if (firstAnswerCorrect == true)
{
label2.Text = "correct";
correctAnswers = correctAnswers + 1;
}
else
{
label2.Text = "incorrect";
wrongAnswers = wrongAnswers + 1;
}
bool thirdAnswerCorrect = CheckAnswer(dataGridView1.Rows[2], textBoxQ3);
if (thirdAnswerCorrect == true)
{
label3.Text = "correct";
correctAnswers = correctAnswers + 1;
}
else
{
label3.Text = "incorrect";
wrongAnswers = wrongAnswers + 1;
}
bool fourthAnswerCorrect = CheckAnswer(dataGridView1.Rows[3], textBoxQ4);
if (fourthAnswerCorrect == true)
{
label4.Text = "correct";
correctAnswers = correctAnswers + 1;
}
else
{
label4.Text = "incorrect";
wrongAnswers = wrongAnswers + 1;
}
bool fifthAnswerCorrect = CheckAnswer(dataGridView1.Rows[4], textBoxQ5);
if (fifthAnswerCorrect == true)
{
label5.Text = "correct";
correctAnswers = correctAnswers + 1;
}
else
{
label5.Text = "incorrect";
wrongAnswers = wrongAnswers + 1;
}
bool sixthAnswerCorrect = CheckAnswer(dataGridView1.Rows[5], textBoxQ6);
if (sixthAnswerCorrect == true)
{
label6.Text = "correct";
correctAnswers = correctAnswers + 1;
}
else
{
label6.Text = "incorrect";
wrongAnswers = wrongAnswers + 1;
}
bool seventhAnswerCorrect = CheckAnswer(dataGridView1.Rows[6], textBoxQ7);
if (seventhAnswerCorrect == true)
{
label7.Text = "correct";
correctAnswers = correctAnswers + 1;
}
else
{
label7.Text = "incorrect";
wrongAnswers = wrongAnswers + 1;
}
bool eighthAnswerCorrect = CheckAnswer(dataGridView1.Rows[7], textBoxQ8);
if (eighthAnswerCorrect == true)
{
label8.Text = "correct";
correctAnswers = correctAnswers + 1;
}
else
{
label8.Text = "incorrect";
wrongAnswers = wrongAnswers + 1;
}
bool ninethAnswerCorrect = CheckAnswer(dataGridView1.Rows[8], textBoxQ9);
if (ninethAnswerCorrect == true)
{
label9.Text = "correct";
correctAnswers = correctAnswers + 1;
}
else
{
label9.Text = "incorrect";
wrongAnswers = wrongAnswers + 1;
}
bool tenthAnswerCorrect = CheckAnswer(dataGridView1.Rows[9], textBoxQ10);
if (tenthAnswerCorrect == true)
{
label10.Text = "correct";
correctAnswers = correctAnswers + 1;
}
else
{
label10.Text = "incorrect";
wrongAnswers = wrongAnswers + 1;
}
label11.Text = ("YOU HAVE SCORED " + correctAnswers + " OUT OF 10");
label12.Text = ("YOU HAVE " + wrongAnswers + " QUESTIONS WRONG");
The code WORKS its just repetitive
EDIT:
This function just calculates the correct and incorrect answers. I have another function which checks if the answer the user input into the textbox is the same as the answer in the (hidden) datagrid
This is the code for that function:
private bool CheckAnswer(DataGridViewRow dataGridViewRow, TextBox textBox)
{
string correctAnswer = dataGridViewRow.Cells["answer"].Value.ToString();
string givenAnswer = textBox.Text;
bool isCorrect = string.Equals(correctAnswer, givenAnswer, StringComparison.CurrentCultureIgnoreCase);
return isCorrect;
}
As I said. Its working but its just repetitive which is not a good sign.
EDIT:
This is the new C# code I am using which is eliminates the code duplication, however I encountered an exception when I tweaked it a bit.
List<TextBox> textboxes = new List<TextBox> { textBoxQ1, textBoxQ2, textBoxQ3, textBoxQ4, textBoxQ5, textBoxQ6, textBoxQ7, textBoxQ8, textBoxQ9, textBoxQ10 };
List<Label> labels = new List<Label> { label1, label2, label3, label4, label5, label6, label7, label8, label9, label10 };
bool temp;
for (int i = 0; i < 10; i++)
{
temp = CheckAnswer(dataGridView1.Rows[i], textboxes[i]);
if (temp == true)
{
labels[i].Text = "correct";
correctAnswers = correctAnswers + 1;
}
else
{
labels[i].Text = "incorrect";
wrongAnswers = wrongAnswers + 1;
}
label11.Text = ("YOU HAVE SCORED " + correctAnswers);
label12.Text = ("YOU HAVE SCORED " + correctAnswers);
}
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index was out of range. Must be non-negative and less than the size of the collection.
The line:
temp = CheckAnswer(dataGridView1.Rows[i], textboxes[i]);
You can make one List<TextBox> and one another List<Label> like below:
List<TextBox> textboxes = new List<TextBox>{textbox1, ....}
List<Label> labels = new List<Label>{label1, label2, ....}
bool temp;
for(int i = 0; i < 10; i++)
{
temp = CheckAnswer(dataGridView1.Rows[i], textBoxes[i]);
if (temp)
{
labels[i].Text = "correct";
correctAnswers = correctAnswers + 1;
}
else
{
labels[i].Text = "incorrect";
wrongAnswers = wrongAnswers + 1;
}
}
May try to reduce repetition in the following way:
List<TextBox> textBoxList = new List<TextBox>() {
textBoxQ1,
textBoxQ2,
...
textBoxQN
};
List<Label> labelList = new List<Label>() {
label1,
label2,
...
labelN
};
for(int i = 0; i < textBoxList.Count; i++) {
bool answerCorrect = CheckAnswer(dataGridView1.Rows[i], textBoxList[i]);
labelList[i].Text = answerCorrect ? "correct" : "incorrect";
correctAnswers += answerCorrect ? 1 : 0;
wrongAnswers += !answerCorrect ? 1 : 0;
}
I'd store all the answer textboxes and correct/incorrect answer labels in an array, like Label[] answerLabels and TextBox[] answerTextBoxes. These arrays should be properly ordered, i.e. answerLabels[0] and answerTextBoxes[0] should correspond to the 1st question, answerLabels[1] and answerTextBoxes[1] should correspond to the 2nd question and so on.
Thereafter this becomes a single for loop:
for(int i = 0; i < answerLabels.Length; i++) {
bool answerCorrect = CheckAnswer(dataGridView1.Rows[i], answerTextBoxes[i]);
if (answerCorrect == true)
{
answerLabels[i].Text = "correct";
correctAnswers = correctAnswers + 1;
}
else
{
answerLabels[i].Text = "incorrect";
wrongAnswers = wrongAnswers + 1;
}
}
A simple solution would be changing everything to strings instead of Booleans. This way you won't need any if statements. Just label1.Text = firstAnswerCorrect which equals (string) either "correct" or "incorrect"
And for the function you would just return "correct" or "incorrect"
Hope this helps.
I have several arrays to collect data from a postgreSQL query. The data comes from RF receiver deployed in the field. As the user establishes the range of frequencies and time for the query the data is displayed on gridview and passed from there to the arrays indicated by an I value and a I + value matching the cell number in the column containing the latitude of the RF receiver. This data is use to plot xy scatter graphs representing (frequency,amplitude), (frequency,bandwidth) etc. I would like to create a list and objects instead of using arrays.
private void button11_Click(object sender, EventArgs e)
dataGridView1.SelectAll();
numCells = dataGridView1.SelectedCells.Count;
for (i = 14; i < (numCells); i += 14)
{
if (i < numCells)
{
if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToString()== 28.464258839)
{
UCS1size += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToStrin()) == 28.42859146)
{
MOCsize += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToStrin()) == 28.490616471)
{
AMsize += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToStrin()) == 28.525409911)
{
UCS2size += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToStrin()) == 28.560529988)
{
LC40size += 1;
}
}
else
{
MessageBox.Show("exiting for loop. numcells: " + numCells);
}
}
double[] freqLC40 = new double[LC40size];
double[] ampMaxLC40 = new double[LC40size];
double[] freqMOC = new double[MOCsize];
double[] ampMaxMOC = new double[MOCsize];
double[] freqUCS1 = new double[UCS1size];
double[] ampMaxUCS1 = new double[UCS1size];
double[] freqUCS2 = new double[UCS2size];
double[] ampMaxUCS2 = new double[UCS2size];
double[] freqAM = new double[AMsize];
double[] ampMaxAM = new double[AMsize];
int LC40idx = 0;
int MOCidx = 0;
int UCS1idx = 0;
int UCS2idx = 0;
int AMsidx = 0;
for (i = 14; i < (numCells); i += 14)
{
if (i < numCells)
{
if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToString())== 28.464258839)
{
freqUCS1[UCS1idx] = Convert.ToDouble(dataGridView1.SelectedCell[i].Value.ToString());
ampMaxUCS1[UCS1idx] = Convert.ToDouble(dataGridView1.SelectedCells[i +9].Value.ToString());
UCS1idx += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i +11].Value.ToString()) == 28.42859146)
{
freqMOC[MOCidx] = Convert.ToDouble(dataGridView1.SelectedCells[i].Value.ToString());
ampMaxMOC[MOCidx] = Convert.ToDouble(dataGridView1.SelectedCells[i +9].Value.ToString());
MOCidx += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToString()) == 28.490616471)
{
freqAM[AMsidx] = Convert.ToDouble(dataGridView1.SelectedCells[i].Value.ToString());
ampMaxAM[AMsidx] = Convert.ToDouble(dataGridView1.SelectedCells[i + 9].Value.ToString());
AMsidx += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToString()) == 28.525409911)
{
freqUCS2[UCS2idx] = Convert.ToDouble(dataGridView1.SelectedCells[i].Value.ToString());
ampMaxUCS2[UCS2idx] = Convert.ToDouble(dataGridView1.SelectedCells[i +9].Value.ToString());
UCS2idx += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToString()) == 28.560529988)
{
freqLC40[LC40idx] = Convert.ToDouble(dataGridView1.SelectedCells[i].Value.ToString());
ampMaxLC40[LC40idx] = Convert.ToDouble(dataGridView1.SelectedCells[i+9].Value.ToString());
LC40idx += 1;
}
}
else
{
MessageBox.Show("exiting for loop. numcells: " + numCells);
}
}
//get XY form LC40
xyForm = new XYplotForm();
xyForm.Plot(freqLC40, ampMaxLC40, "LC-40 Max Amplitude");
xyForm.Show();
I am developing an attendance application using asp.net. I am showing the record of the person according to their ID from day 1 to last day of the month and I also want to display their all details when I click on particular date.
I am using DataRow and create dynamic row of the month according to the day(s) of the month and displaying their data (Present or Absent).
I am not Understanding how can I convert (present or absent) as a link in gridview so that I can fetch all the details by click them.
Here is the code :
private void BindData()
{
string queryText = "";
DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Columns.Add("UserID");
table.Columns.Add("Employee Name");
table.Columns.Add("Location");
//table.Columns.Add("Days");
row[0] = Convert.ToString("");
row[1] = Convert.ToString("");
row[2] = Convert.ToString("");
num = DateTime.DaysInMonth(DateTime.Now.Year, Convert.ToInt32(this.drpmonth.SelectedValue));
string str2 = Convert.ToString(Convert.ToDateTime(string.Concat(new object[] { "01/", this.drpmonth.SelectedValue, "/", DateTime.Now.Year })).ToString("d"));
for (int i = 1; i <= num; i++)
{
table.Columns.Add(Convert.ToString(i));
row[i + 2] = this.GetAbbriviateDay(Convert.ToString(Convert.ToDateTime(string.Concat(new object[] { i, "/", this.drpmonth.SelectedValue, "/", DateTime.Now.Year })).DayOfWeek));
}
table.Rows.Add(row);
if (!string.IsNullOrEmpty(this.txtemplID.Text) && (this.txtemplID.Text.Trim() != ""))
{
queryText = "SELECT EmpID, CONCAT(Fname, ' ', Lname) AS EmployeeName FROM **[table_name]** where `EmpID`='" + this.txtemplID.Text.Trim() + "'";
}
else
{
queryText = "SELECT EmpID, CONCAT(Fname, ' ', Lname) AS EmployeeName FROM **[table_name]** order by EmpID desc";
}
DataTable table2 = AssetDatabaseConnection.ExecuteQuery(queryText);
DataTable table3 = AssetDatabaseConnection.ExecuteQuery("Select a.EmpID,b.location_name as Location, b.Currentt_Date,case When sum(timestampdiff(HOUR,b.In_Entry,b.Out_Entry)) is null Then '0.00' ELSE cast(sum(timestampdiff(Minute,b.In_Entry,b.Out_Entry))/60 as char) End as TotalHors from GPS_Login a left join **[table_name]** as b on a.EmpID=b.User_ID where month(b.Currentt_Date)='" + this.drpmonth.SelectedValue + "' and year(b.Currentt_Date)=YEAR(NOW()) group by b.Currentt_Date,a.EmpID order by b.Currentt_Date asc");
if (table2.Rows.Count > 0)
{
for (int j = 0; j < table2.Rows.Count; j++)
{
int num4 = 0;
row = table.NewRow();
ViewState["EmpID"] = Convert.ToString(table2.Rows[j]["EmpID"]);
row[0] = Convert.ToString(table2.Rows[j]["EmpID"]);
row[1] = Convert.ToString(table2.Rows[j]["EmployeeName"]);
ViewState["EmpName"] = Convert.ToString(table2.Rows[j]["EmployeeName"]);
//row[2] = Convert.ToString(table2.Rows[j]["Location"]);
for (int k = 0; k < num; k++)
{
num4 = 0;
if (table3.Rows.Count > 0)
{
foreach (DataRow row2 in table3.Rows)
{
string str3 = Convert.ToDateTime(row2["Currentt_Date"]).ToString("d");
ViewState["Curr_Date"] = Convert.ToDateTime(row2["Currentt_Date"]).ToString("yyyy-MM-dd");
string str4 = Convert.ToDateTime(str2).AddDays((double)k).ToString("dd/MM/yyyy");
string str5 = Convert.ToString(table2.Rows[j]["EmpID"]);
string str6 = Convert.ToString(row2["EmpID"]);
string Loc = Convert.ToString(row2["Location"]);
if ((str3 == str4) && (str5 == str6))
{
num4 = 1;
if (Convert.ToDouble(row2["TotalHors"]) >= 9.0)
{
row[k + 3] = "P";
row[2] = Loc;
}
else if (Math.Round(Convert.ToDouble(row2["TotalHors"]), 2) == 0.0)
{
row[k + 3] = "A";
row[2] = Loc;
}
else
{
row[k + 3] = "S";
//row[k + 3] = "S(" + Math.Round(Convert.ToDecimal(row2["TotalHors"]), 2) + ")";
//ViewState["ShortLeave"] = "S(" + Math.Round(Convert.ToDecimal(row2["TotalHors"]), 2) + ")";
row[2] = Loc;
}
}
}
if (num4 == 0)
{
row[k + 3] = "A";
}
}
}
table.Rows.Add(row);
}
}
this.grdattendanceDetail.DataSource = table;
this.grdattendanceDetail.DataBind();
}
and after that I am creating dynamic link button inside gridview using Rowdatabound but after click on link it conver as a text here is the code of rowdatabound :
protected void grdattendanceDetail_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int days = DateTime.DaysInMonth(DateTime.Today.Year, int.Parse(Session["SelectedMonth"].ToString()));
days += 3;
for (int i = 3; i <= days; i++)
{
if (e.Row.Cells[i].Text == "A")
{
LinkButton lnkbtn = new LinkButton();
lnkbtn.ID = "AttendanceID";
lnkbtn.Text = "A";
lnkbtn.ToolTip = "Absent";
//lnkbtn.BackColor = System.Drawing.Color.Red;
//lnkbtn.ForeColor = System.Drawing.Color.White;
lnkbtn.ForeColor = System.Drawing.ColorTranslator.FromHtml("#8C4510");
//lnkbtn.Click += new EventHandler(lnkbtn_Click);
lnkbtn.Click += new System.EventHandler(AttendanceID_Click);
e.Row.Cells[i].Controls.Add(lnkbtn);
}
else if(e.Row.Cells[i].Text == "P")
{
LinkButton lnkbtn = new LinkButton();
lnkbtn = new LinkButton();
lnkbtn.ID = "AttendanceID";
lnkbtn.Text = "P";
lnkbtn.ToolTip = "Present";
lnkbtn.ForeColor = System.Drawing.ColorTranslator.FromHtml("#8C4510");
//lnkbtn.Click += new EventHandler(lnkbtn_Click);
lnkbtn.Click += new System.EventHandler(AttendanceID_Click);
e.Row.Cells[i].Controls.Add(lnkbtn);
}
else if (e.Row.Cells[i].Text == "S")
{
LinkButton lnkbtn = new LinkButton();
lnkbtn = new LinkButton();
lnkbtn.ID = "AttendanceID";
lnkbtn.Text = "S";
lnkbtn.ToolTip = "Short Leave";
lnkbtn.ForeColor = System.Drawing.ColorTranslator.FromHtml("#8C4510");
//lnkbtn.Click += new EventHandler(AttendanceID_Click);
lnkbtn.Click += new System.EventHandler(AttendanceID_Click);
e.Row.Cells[i].Controls.Add(lnkbtn);
}
}
}
}
catch (Exception ex)
{
Response.Write(#"<script>alert('" + ex.Message + "')</script>");
}
}
screenshot of the output :
A , S , P are links so that I can show one day details of the candidate.
I just started with ASP.NET and I'm having trouble with displaying a result from a loop. For example:
int x = 0;
while (x < 10) {
Label1.Text = x+""; // This will show only result 9 ( last result ).
x++;
}
How do I show all results instead of only one?
Instead of:
Label1.Text = x+"";
Do:
Label1.Text = Label1.Text + x;
This will show only result 9 ( last result ).
Yes because you assign a new value to Label1.Text property in every iteration.
Try this instead;
int x = 0;
while (x < 10)
{
Label1.Text = Label1.Text + x;
x++;
}
Or instead define a string value outside of while and add it this int values inside of your loop and assign your .Text value outside of your loop like;
int x = 0;
string s = "";
while (x < 10)
{
s += x;
x++;
}
Label1.Text = s;
Or use StringBuilder would be better if you use a lot of numbers;
int x = 0;
StringBuilder s = new StringBuilder();
while (x < 10)
{
s.Append(x);
x++;
}
Label1.Text = s.ToString();
int x = 0;
while (x < 10) {
Label1.Text += x+""; // This will show "123456789".
x++;
}
You need to add to the text in each iteration.
If you want to show a list of them :
Label1.Text += "," + x.ToString();
Or
Label1.Text = Label1.Text + "," + x.ToString();
Either way will produce the result :
0,1,2,3,4,5,6,7,8,9
You should accumulate the values of each element, something like this:
int x = 0;
while (x < 10) {
Label1.Text = Label1.Text + x;
x++;
}
int x = 0;
while (x < 10) {
Label1.Text += x.ToString();
x++;
}
You could use string builder
try this:
StringBuilder sb = new StringBuilder();
int x = 0;
while (x < 10) {
sb.Append(x);
sb.Append(" ");
x++;
}
Label1.Text = sb.ToString();
Please use the code as below, you gotta assign a new id to Label1.Text in every iteration.
int x = 0;
while (x < 10)
{
label1.Text += x.ToString();
x++;
}
Replace
Label1.Text = x+"";
with
Label1.Text = Label1.Text + x.ToString();
+= append string to variable instead of replacing so,
int x = 0;
while (x < 10) {
Label1.Text += x+" "; //append space to separate
x++;
}