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.
Related
I am trying to convert a program from console to windows form but the problem is that the output is not showing on my textbox. My program is that user inputs how many number of rows.
int n = int.Parse(textbox1.Text);
int counter1 = 1,counter2 = 1,size = n + n -1;
for(int i = 0;i<size;i++){
for(int j = 0;j<size;j++){
if(i<n-1){
if(j<n-1){
if(i == j){
textBox2.Text = "{0} " + counter1;
counter1++;}
else{
textBox2.Text = " ";
} }
else{
if(i + j == size-1){
textBox2.Text = "{0} " + counter2;
counter2++;}
else{
textBox2.Text = " ";
}
} }
else if(i == n- 1 && j == n-1){
textBox2.Text = "{0} " + counter1;
counter1--;
counter2--; }
else if(i == n-1 && j != n-1){
textBox2.Text = " ";
}
else if(i > n-1){
if(j>n-1){
if(i == j){
textBox2.Text = "{0} " + counter1;
counter1--;
}
else{
textBox2.Text = " ";
} }
else
{
if(i + j == size-1){
textBox2.Text = "{0} " + counter2;
counter2--;
}
else{
textBox2.Text = " ";
}
} } }
textBox2.Text = " ";
}
The program is to display the input x number pattern. Thanks in advance.
You are resetting the text of textBox2 every time. You should use the += operator instead of =.
Side note: You should also use the special '\n' character when you need a new line.
So, I need to look through the file and fill and 2d array with data from the file. I couldn't figure any better way to do that than this, but this code just completly freezes. Here's the code.
The idea is that I'm gonna look through all of the text in a source file, then I'm gonna check if a line contains something I need and, if so, I will make additions to my 2D array, that I will then write to a different txt file.
string[,] FileBase = new string[100,100];
DateTime Date = DateTime.UtcNow;
string time = Date.ToString();
time = time.Replace(':', '.');
string ReportPath = Directory.GetCurrentDirectory() + "\\Report from " + time + ".txt";
int Value = 0;
int i = 0, j = 0;
string item;
int controlD = 0;
int sensor = 0;
int p = 0;
bool loadcell = false;
bool possensor = false;
int smth = 0;
string curr = comboBox1.SelectedItem.ToString();
curr = curr.Remove(0, curr.IndexOf("RCU") + 3);
int current = Convert.ToInt32(curr);
string localpath = path + "\\control\\RCU" + curr + "\\cfg\\RCU" + curr + ".cfg";
FileStream file1 = new FileStream(localpath, FileMode.Open);
StreamReader reader = new StreamReader(file1);
while ((item = reader.ReadLine()) != null)
{
for (i = p; i < 100; i++)
{
for (j = 0; j < 1000; i++)
{
if (item.Contains("Signal_Sensor"))
{
sensor++;
FileBase[i, j] = "Signal_SensorA" + sensor;
break;
}
else if (item.Contains("Signal_PositionA"))
{
controlD++;
FileBase[i, j] = "Signal_PositionA" + controlD;
break;
}
else if (item.Contains("Division") && (controlD != 0))
{
FileBase[i, j] = "Division";
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
else if (item.Contains("LowerLimitExternal"))
{
FileBase[i, j] = "LowerLimitExternal";
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
else if (item.Contains("UpperLimitExternal"))
{
FileBase[i, j] = "UpperLimitExternal";
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
else if (item.Contains("LowerLimit"))
{
FileBase[i, j] = "LowerLimit";
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
else if (item.Contains("UpperLimit"))
{
FileBase[i, j] = "UpperLimit";
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
else if (item.Contains("LoadCell"))
{
loadcell = true;
break;
}
else if (item.Contains("PositionSensor"))
{
possensor = true;
break;
}
else if (item.Contains("EnableSensorA" + smth))
{
smth++;
FileBase[i, j] = "EnableSensorA" + smth;
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
else if (item.Contains("InvertSensorA"))
{
smth++;
FileBase[i, j] = "InvertSensorA" + (smth - 3);
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
if (smth ==6)
{
smth = 0;
break;
}
}
p = i;
break;
}
}
reader.Close();
File.Create(ReportPath);
FileStream ReportFill = new FileStream(ReportPath, FileMode.Open);
StreamReader reader1 = new StreamReader(ReportFill);
WriteArray();
reader1.Close();
Thanks in advance!
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";
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.
private void btnSaveStudy_Click(object sender, EventArgs e)
{
string valueFromlbl = string.Empty;
for(int i = 0; i < tableContent.Rows.Count; i++)
{
for(int j = 0; j < tableContent.Rows[i].Cells.Count; j++)
{
foreach(Control ctrl in tableContent.Rows[i].Cells[j].Controls)
{
Label lbl = ctrl as Label;
if(lbl != null)
{
valueFromlbl = lbl.Text;
}
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
HtmlTable table = null;
HtmlTableRow row = null;
HtmlTableCell cell = null;
studyNumber = studyNumber + 1;
uniqueID = uniqueID + 1;
for(int i = 0; i < 5; i++)
{
table = new HtmlTable();
row = new HtmlTableRow();
tableContent.Controls.AddAt(i, row);
for(int j = 0; j < 3; j++)
{
cell = new HtmlTableCell();
cell.Attributes.Add("Class", "csstablelisttd");
row.Attributes.Add("Class", "csstextheader");
row.Controls.AddAt(j, cell);
if(i == 0 && j == 0)
{
cell.InnerText = "Study : " + Convert.ToInt32(studyNumber);
}
else if(i == 1 && j == 0)
{
cell.InnerText = "Modality" + " : " + modality;
}
else if(i == 2 && j == 0)
{
cell.InnerText = "Start Date" + " : " + DateTime.Now.ToString("dd-MMM-yyyy");
}
else if(i == 3 && j == 0)
{
cell.InnerText = "Accession Number" + " : " + accessionNumber;
}
else if(i == 4 && j == 0)
{
Button btnSaveStudy = new Button();
btnSaveStudy.ID = "btnSaveStudy" + uniqueID;
btnSaveStudy.Text = "Save";
btnSaveStudy.Attributes.Add("Class", "cssbutton");
cell.Controls.Add(btnSaveStudy);
btnSaveStudy.Click += new EventHandler(btnSaveStudy_Click);
}
if(i == 1 && j == 1)
{
cell.InnerText = "AE Title" + " : " + schedule_Station_AE_Title;
}
else if(i == 1 && j == 2)
{
cell.InnerText = "Station Name" + " : " + schedule_Station_Name;
}
else if(i == 2 && j == 1)
{
cell.InnerText = "Start time" + " : " + startTime;
}
else if(i == 3 && j == 1)
{
cell.InnerText = "End time" + " : " + endTime;
}
else if(i == 2 && j == 2)
{
Label lblPriority = new Label();
lblPriority.ID = "lblPriority" + uniqueID;
lblPriority.Text = "Priority : ";
DropDownList ddlPriority = new DropDownList();
ddlPriority.ID = "ddlPriority" + uniqueID;
ddlPriority.Attributes.Add("Class", "csstextbox");
ddlPriority.Items.Add(new ListItem("MEDIUM", "4"));
ddlPriority.Items.Add(new ListItem("STAT", "1"));
ddlPriority.Items.Add(new ListItem("HIGH", "2"));
ddlPriority.Items.Add(new ListItem("ROUTINE", "3"));
ddlPriority.Items.Add(new ListItem("LOW", "5"));
cell.Controls.Add(lblPriority);
cell.Controls.Add(ddlPriority);
}
else if(i == 3 && j == 2)
{
Label lblStudy = new Label();
lblStudy.ID = "lblStudy" + uniqueID;
lblStudy.Text = "Study : ";
DropDownList ddlStudyList = new DropDownList();
ddlStudyList = BindStudy(ddlStudyList, Convert.ToInt32(acqModalityID), uniqueID);
ddlStudyList.Attributes.Add("Class", "csstextbox");
cell.Controls.Add(lblStudy);
cell.Controls.Add(ddlStudyList);
}
}
}
}}
I have added controls to table cell but not find any control
This appears to be an issue with the execution order. Remember that your controls are not added until after your click event. So when your button click fires, the controls need to have been re-added before you can check for their existence.
(I would post this as a comment, but evidently, as I am new, I don't have enough points)
pass in the Page as the root and see if the control you are looking for comes back
private Control FindControlRecursive(Control rootControl, string controlID)
{
if (rootControl.ID == controlID) return rootControl;
foreach (Control controlToSearch in rootControl.Controls)
{
Control controlToReturn =
FindControlRecursive(controlToSearch, controlID);
if (controlToReturn != null) return controlToReturn;
}
return null;
}
You have simply forgotten to add the table itself to the page's control-collection.
Page.Controls.Add(table);
(it would be better to add it to a container control like PlaceHolder or Panel instead)