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.
Related
I have just started working with EPPlus. i have data table which has some numeric data and formula. when i load data table by EPPlus and save to excel then formula not evaluated i found when i open the same excel file. formula lies in excel cell as string like SUM(A3:B3)
To evaluate formulate i have tried many options of EPPLUS and those are listed here
pack.Workbook.Worksheets["Test"].Calculate();
pack.Workbook.Worksheets["Test"].Cells["A3"].Calculate();
pack.Workbook.Worksheets["Test"].Cells["B3"].Calculate();
ws.Calculate();
Here i am referring my full sample code where formula not working. please have a look and tell me what i need to add in my code to evaluate formula.
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = GetDataTable();
string path = #"d:\EPPLUS_DT_Excel.xlsx";
Stream stream = File.Create(path);
using (ExcelPackage pack = new ExcelPackage())
{
ExcelWorksheet ws = pack.Workbook.Worksheets.Add("Test");
ws.Cells["A1"].LoadFromDataTable(dt, false);
//pack.Workbook.Worksheets["Test"].Calculate();
//pack.Workbook.Worksheets["Test"].Cells["A3"].Calculate();
//pack.Workbook.Worksheets["Test"].Cells["B3"].Calculate();
ws.Calculate();
pack.SaveAs(stream);
stream.Close();
MessageBox.Show("Done");
}
}
public DataTable GetDataTable()
{
string strSum = "", strColName, strImmediateOneUp = "", strImmediateTwoUp = "";
int startsum = 0;
int currow = 0;
bool firstTimeSum = true;
int NumRows = 3;
int NumColumns = 2;
DataTable dt = new DataTable();
for (int col = 0; col < NumColumns; col++)
{
strColName = GenerateColumnText(col);
DataColumn datacol = new DataColumn(strColName, typeof(object));
dt.Columns.Add(datacol);
}
for (int row = 0; row < NumRows; row++)
{
dt.Rows.Add();
for (int col = 0; col < NumColumns; col++)
{
if (row < 2)
{
dt.Rows[row][col] = Convert.ToInt32(new Random().Next(1, NumRows));
}
else
{
if (firstTimeSum)
{
if (row - currow == 2)
{
currow = row;
startsum = 0;
firstTimeSum = false;
}
else
{
startsum = 1;
}
}
else
{
if (row - currow == 3)
{
currow = row;
startsum = 0;
}
}
if (startsum == 0)
{
strColName = GenerateColumnText(col);
strImmediateOneUp = strColName + ((row + 1) - 1).ToString();
strImmediateTwoUp = strColName + ((row + 1) - 2).ToString();
strSum = string.Format("+SUM({0}:{1})", strImmediateTwoUp, strImmediateOneUp);
dt.Rows[row][col] = strSum;
}
else
{
dt.Rows[row][col] = Convert.ToInt32(new Random().Next(1, NumRows));
}
}
}
startsum = 1;
}
return dt;
}
private string GenerateColumnText(int num)
{
string str = "";
char achar;
int mod;
while (true)
{
mod = (num % 26) + 65;
num = (int)(num / 26);
achar = (char)mod;
str = achar + str;
if (num > 0) num--;
else if (num == 0) break;
}
return str;
}
When adding a formula to a cell you use the Formula property. When you load a range from a DataTable using LoadFromDataTable it has no way of knowing that some of the values are meant to be interpreted as formulas.
You can use LoadDataTable to populate the cells on which the formulas will operate, but for the formulas you'll need to set the Formula property.
I have a set of codes to export grid view data to excel using EPPLUS. I am able to export the data to EPPLUS. But how do I export the colour of the font to excel as well? Can I set the dynamic coding for the font colour if ..... colour = green if ..... colour = red?
Thus I will need column4 to be coloured as well according to the value I set.
The below codes is how I set dynamically for gridview:
if (e.Row.RowType == DataControlRowType.DataRow)
{
TableCell cell = e.Row.Cells[16];
int Num = int.Parse(cell.Text);
if (Num >= 1&& Num <= 11)
{
cell.ForeColor = Color.Green;
}
if (Num >= 12&& Num <= 39)
{
cell.ForeColor = Color.Orange;
}
..........
}
The codes for my export:
protected void EXPORT_BUTTON_Click(object sender, EventArgs e)
{
ExcelPackage package = new ExcelPackage();
ExcelWorksheet Grid = package.Workbook.Worksheets.Add("ORSA ASSESSMENTS");
DataTable Gridview1 = new DataTable();
for (int i = 0; i < Gridview1.Columns.Count; i++)
{
Gridview1.Columns.Add("column" + i.ToString());
}
foreach (GridViewRow row in Gridview1.Rows)
{
DataRow dr = Gridview1.NewRow();
for (int j = 0; j < Gridview1.Columns.Count; j++)
{
row.Cells[j].Text = row.Cells[j].Text.Replace(" ", " ");
dr["column" + j.ToString()] = row.Cells[j].Text;
}
Gridview1.Rows.Add(dr);
}
Grid.Cells["A1"].LoadFromDataTable(Gridview1, true);
using (ExcelRange rng = Grid.Cells["A1:Z1"])
{
rng.Style.Font.Bold = true;
}
Grid.Cells[ORSA.Dimension.Address].AutoFitColumns();
var FolderPath = ServerName + DirectoryLocation + DirectoryFolder + ExportsFolder;
var filename = ExcelName + #"_" + ".xlsx";
var filepath = new FileInfo(Path.Combine(FolderPath, filename));
Response.Clear();
package.SaveAs(filepath);
Response.AddHeader("content-disposition", "attachment; filename=" + filename + ";");
Response.Charset = "";
Response.ContentType = "application/vnd.xlsx";
Response.TransmitFile(filepath.FullName);
Response.End();
}
Thus how can I do in my export codes so that I can export or set the forecolour dynamically upon exporting?
thanks
After this line
Grid.Cells["A1"].LoadFromDataTable(Gridview1, true);
Do a looping to loop the count of your DataTable
Example
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
DataTable dt = new DataTable();
// Create Column
for(int i = 0; i < 5; i++)
dt.Columns.Add("column" + i, typeof(int));
for (int i = 0; i < 10; i++)
dt.Rows.Add(i, i+1, i+2, i+3, i+4);
GenerateExcel(dt);
}
}
private void GenerateExcel(DataTable dt)
{
using (ExcelPackage pkg = new ExcelPackage())
{
ExcelWorksheet ws = pkg.Workbook.Worksheets.Add("Sheet1");
int num = 0;
string value = string.Empty;
ws.Cells[1, 1].LoadFromDataTable(dt, true);
// Get Your DataTable Count
int count = dt.Rows.Count;
int countCol = dt.Columns.Count;
bool isHeader = true;
for (int i = 0; i < count; i++ )
{
// Set Border
for (int j = 1; j <= countCol; j++)
{
// Set Border For Header. Run once only
if (isHeader) ws.Cells[1, j].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin, System.Drawing.Color.Black);
ws.Cells[2 + i, j].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin, System.Drawing.Color.Black);
}
// Set to false
isHeader = false;
// Cells 2 + i == Rows, Wondering start with 2 because your 1st rows is Title so 2 is the value
// Cells 2 == Column make sure your column is fix
value = ws.Cells[2 + i, 2].Value + ""; // You can use .ToString() if u sure is not null
// Parse
int.TryParse(value, out num);
// Check
if (num >= 1 && num <= 11)
ws.Cells[2 + i, 2].Style.Font.Color.SetColor(System.Drawing.Color.Green);
else if (num >= 12 && num <= 39)
ws.Cells[2 + i, 2].Style.Font.Color.SetColor(System.Drawing.Color.Orange);
}
pkg.SaveAs(new FileInfo("C:\\Test.xlsx"));
}
}
I have write code as following :
protected void Page_Load(object sender, EventArgs e)
{
Literal lt;
Label lb;
//Get ContentPlaceHolder
ContentPlaceHolder content = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
pnlStartDate = new Panel();
pnlStartDate.ID = "pnlStartDate";
// pnlStartDate.BorderWidth = 1;
pnlStartDate.Width = 100;
grvWorkOrder.Rows[rowIndex].Cells[13].Controls.Add(pnlStartDate);
lt = new Literal();
lt.Text = "<br />";
grvWorkOrder.Rows[rowIndex].Cells[13].Controls.Add(lt);
//Button To add TextBoxes
Button btnAddTxt = new Button();
btnAddTxt.ID = "btnAddTxt";
btnAddTxt.Text = "Add TextBox";
btnAddTxt.CausesValidation = false;
btnAddTxt.Click += new System.EventHandler(btnAddTextbox_Click);
grvWorkOrder.Rows[rowIndex].Cells[10].Controls.Add(btnAddTxt);
if (IsPostBack)
{
RecreateDateControls("txtStartDateDynamic", "TextBox", "img1StartDateDynamic", "ImageButton", "ceStartDateDynamic", "CalendarExtender");
}
rowIndex++;
}
}
}
}
protected void btnAddTextbox_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
if (btn.ID == "btnAddTxt")
{
Literal lt = new Literal();
lt.Text = "<br />";
int cntStartDate = FindOccurence("txtStartDateDynamic");
TextBox txt4 = new TextBox();
txt4.ID = "txtStartDateDynamic-" + Convert.ToString(cntStartDate + 1);
txt4.Width = 90;
pnlStartDate.Controls.Add(txt4);
int cntImgStartDate = FindOccurence("img1StartDateDynamic");
ImageButton img1StartDateDynamic = new ImageButton();
img1StartDateDynamic.ID = "img1StartDateDynamic-" + Convert.ToString(cntImgStartDate + 1);
img1StartDateDynamic.ImageUrl = "Images/calender.jpg";
img1StartDateDynamic.Width = 25;
img1StartDateDynamic.CausesValidation = false;
pnlStartDate.Controls.Add(img1StartDateDynamic);
int cntCeStartDate = FindOccurence("ceStartDateDynamic");
CalendarExtender ceStartDateDynamic = new CalendarExtender();
ceStartDateDynamic.ID = "ceStartDateDynamic-" + Convert.ToString(cntCeStartDate + 1);
ceStartDateDynamic.Enabled = true;
ceStartDateDynamic.TargetControlID = "txtStartDateDynamic-" + Convert.ToString(cntCeStartDate + 1);
ceStartDateDynamic.PopupButtonID = "img1StartDateDynamic-" + Convert.ToString(cntCeStartDate + 1);
ceStartDateDynamic.Format = "yyyy/MM/dd";
pnlStartDate.Controls.Add(ceStartDateDynamic);
pnlStartDate.Controls.Add(lt);
}
}
private int FindOccurence(string substr)
{
string reqstr = Request.Form.ToString();
return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length);
}
private void RecreateDateControls(string ctrlPrefix1, string ctrlType1, string ctrlPrefix2, string ctrlType2, string ctrlPrefix3, string ctrlType3)
{
string[] ctrls1 = Request.Form.ToString().Split('&');
string[] ctrls2 = Request.Form.ToString().Split('&');
string[] ctrls3 = Request.Form.ToString().Split('&');
int cnt1 = FindOccurence(ctrlPrefix1);
int cnt2 = FindOccurence(ctrlPrefix2);
int cnt3 = FindOccurence(ctrlPrefix3);
if (cnt1 > 0 && cnt2 > 0 && cnt3 > 0)
{
Literal lt;
for (int k = 1; k <= cnt1; k++)
{
for (int i = 0; i < ctrls1.Length ; i++)
{
if (ctrls1[i].Contains(ctrlPrefix1 + "-" + k.ToString()))
{
string ctrlName1 = ctrls1[i].Split('=')[0];
string ctrlValue1 = ctrls1[i].Split('=')[1];
if (ctrls1[i].Contains(ctrlPrefix2 + "-" + k.ToString()))
{
string ctrlName2 = ctrls1[i].Split('=')[0];
if (ctrls1[i].Contains(ctrlPrefix3 + "-" + k.ToString()))
{
string ctrlName3 = ctrls1[i].Split('=')[0];
if (ctrlType1 == "TextBox" && ctrlPrefix1 == "txtStartDateDynamic" && ctrlType2 == "ImageButton" && ctrlPrefix2 == "img1StartDateDynamic" && ctrlType3 == "CalendarExtender" && ctrlPrefix3 == "ceStartDateDynamic")
{
TextBox txt4 = new TextBox();
txt4.ID = ctrlName1;
txt4.Text = ctrlValue1;
txt4.Width = 90;
pnlStartDate.Controls.Add(txt4);
ImageButton img1StartDateDynamic = new ImageButton();
img1StartDateDynamic.ID = ctrlName2;
img1StartDateDynamic.ImageUrl = "Images/calender.jpg";
img1StartDateDynamic.Width = 25;
img1StartDateDynamic.CausesValidation = false;
pnlStartDate.Controls.Add(img1StartDateDynamic);
CalendarExtender ceStartDateDynamic = new CalendarExtender();
ceStartDateDynamic.ID = ctrlName3;
ceStartDateDynamic.Enabled = true;
ceStartDateDynamic.TargetControlID = ctrlName1;
ceStartDateDynamic.PopupButtonID = ctrlName2;
ceStartDateDynamic.Format = "yyyy/MM/dd";
pnlStartDate.Controls.Add(ceStartDateDynamic);
lt = new Literal();
lt.Text = "<br />";
pnlStartDate.Controls.Add(lt);
}
}
}
}
break;
}
}
}
}
But the problem is in RecreateDateControls() function ImageButton Counter cnt2 is zero therefore previous controls are not recreated what should i do for it.
go through the link..
create Dynamic Controls
This code works fine for first two times,i.e ,when i click on "Add more solution" it creates a new row and controls respectively but when i click on "Add more solution" for the third time and "add step" button respective to that,,it creates problem.
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < TotalNumberAdded; i++)
{
AddControls((i + 1), plcSolution);
}
for (int i = 0; i < TotalNumberSolAdded; i++)
{
AddMoreControls((i + 1), plcAddMoreSolution, 1);
Button b = (Button)plcAddMoreSolution.FindControl("btn" + (i+1));
for (int j = 0; j < TotalNumberSolStepAdded; j++)
{
AddMoreStepControls((j + 1), plcAddMoreSolution);
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
TotalNumberAdded++;
AddControls(TotalNumberAdded, plcSolution);
}
private void AddControls(int controlNumber, PlaceHolder plc)
{
TextBox txtBoxSolution = new TextBox();
Label lblSolution = new Label();
txtBoxSolution.ID = "txtBoxSolution" + controlNumber;
txtBoxSolution.TextMode = TextBoxMode.MultiLine;
txtBoxSolution.Width = 470;
txtBoxSolution.Height = 50;
lblSolution.ID = "lblSolution" + controlNumber;
lblSolution.Text = "Step " + (controlNumber + 1) + ": ";
lblSolution.Width = 200;
plc.Controls.Add(lblSolution);
plc.Controls.Add(txtBoxSolution);
}
protected int TotalNumberAdded
{
get { return (int)(ViewState["TotalNumberAdded"] ?? 0); }
set { ViewState["TotalNumberAdded"] = value; }
}
protected void btnAlternate_Click(object sender, EventArgs e)
{
lblSol.Text = "Solution 1";
string str = (string)ViewState["btnId"];
if (str != null)
{
btn = (Button)plcAddMoreSolution.FindControl(str);
btn.Visible = false;
}
btnAdd.Visible = false;
TotalNumberSolAdded++;
AddMoreControls(TotalNumberSolAdded, plcAddMoreSolution,1);
}
protected int TotalNumberSolAdded
{
get { return (int)(ViewState["TotalNumberSolAdded"] ?? 0); }
set { ViewState["TotalNumberSolAdded"] = value; }
}
private void AddMoreControls(int controlNumber, PlaceHolder plc,int n)
{
TextBox txtBoxMoreSolution = new TextBox();
Label lblMoreSolution = new Label();
btn = new Button();
btn.Text = "add step";
btn.ID = "btn" + controlNumber;
btn.Click += new EventHandler(btn_Click);
ViewState["btnId"] = btn.ID;
Label lbl = new Label();
lbl.Text = "soltuion" + (controlNumber + 1);
lbl.ID = "moreSolution" + (controlNumber + 1);
lbl.Font.Size = 20;
lbl.Font.Underline = true;
txtBoxMoreSolution.ID = "txtBoxMoreSolution" + controlNumber;
txtBoxMoreSolution.TextMode = TextBoxMode.MultiLine;
txtBoxMoreSolution.Width = 470;
txtBoxMoreSolution.Height = 50;
lblMoreSolution.ID = "lblMoreSolution" + controlNumber;
lblMoreSolution.Text = "Step " + n + ": ";
lblMoreSolution.Width = 200;
plc.Controls.Add(lbl);
plc.Controls.Add(lblMoreSolution);
plc.Controls.Add(txtBoxMoreSolution);
plc.Controls.Add(btn);
}
private void btn_Click(object sender, EventArgs e)
{
TotalNumberSolStepAdded++;
AddMoreStepControls(TotalNumberSolStepAdded, plcAddMoreSolution);
}
protected int TotalNumberSolStepAdded
{
get { return (int)(ViewState["TotalNumberSolStepAdded"] ?? 0); }
set { ViewState["TotalNumberSolStepAdded"] = value; }
}
private void AddMoreStepControls(int controlNumber, PlaceHolder plc)
{
TextBox txtBoxMoreStepSolution = new TextBox();
Label lblMoreStepSolution = new Label();
txtBoxMoreStepSolution.ID = "txtBoxMoreStepSolution" + controlNumber;
txtBoxMoreStepSolution.TextMode = TextBoxMode.MultiLine;
txtBoxMoreStepSolution.Width = 470;
txtBoxMoreStepSolution.Height = 50;
lblMoreStepSolution.ID = "lblMoreStepSolution" + controlNumber;
lblMoreStepSolution.Text = "Step " + (controlNumber +1) + ": ";
lblMoreStepSolution.Width = 200;
plc.Controls.Add(lblMoreStepSolution);
plc.Controls.Add(txtBoxMoreStepSolution);
}
this code will help you.. it works fine...
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < TotalNumberAdded; i++)
{
AddControls(i + 1);
}
for (int i = 0; i < TotalNumberSolAdded; i++)
{
AddMoreControls((i + 1), 1);
DataTable dt = (DataTable)ViewState["t"];
if (dt != null)
{
if ((TotalNumberSolAdded - dt.Rows.Count == 1) && (counter1 == dt.Rows.Count))
{
break;
}
if (i != 0)
{
for (int k = 0; k <= i; k++)
{
int a1 = int.Parse(dt.Rows[k][0].ToString());
b = a1 + b;
}
start = b - int.Parse(dt.Rows[i][0].ToString());
}
else
{
b = int.Parse(dt.Rows[i][0].ToString());
start = 0;
}
for (int j = start; j < b; j++)
{
counter++;
AddMoreStepControls((j + 1), counter);
}
b = 0;
counter = 0;
counter1++;
}
}
}
private void AddControls(int controlNumber)
{
TextBox txtBoxSolution = new TextBox();
Label lblSolution = new Label();
txtBoxSolution.ID = "txtBoxSolution" + controlNumber;
txtBoxSolution.TextMode = TextBoxMode.MultiLine;
txtBoxSolution.Width = 470;
txtBoxSolution.Height = 50;
lblSolution.ID = "lblSolution" + controlNumber;
lblSolution.Text = "Step " + (controlNumber + 1) + ": ";
lblSolution.Width = 200;
plcSolution.Controls.Add(lblSolution);
plcSolution.Controls.Add(txtBoxSolution);
}
protected int TotalNumberAdded
{
get { return (int)(ViewState["TotalNumberAdded"] ?? 0); }
set { ViewState["TotalNumberAdded"] = value; }
}
protected void btnAlternate_Click(object sender, EventArgs e)
{
Number = 0;
lblSol.Text = "Solution 1";
string str = (string)ViewState["btnId"];
if (str != null)
{
btn = (Button)plcAddMoreSolution.FindControl(str);
btn.Visible = false;
}
btnAdd.Visible = false;
TotalNumberSolAdded++;
AddMoreControls(TotalNumberSolAdded, 1);
}
protected int TotalNumberSolAdded
{
get { return (int)(ViewState["TotalNumberSolAdded"] ?? 0); }
set { ViewState["TotalNumberSolAdded"] = value; }
}
private void AddMoreControls(int controlNumber, int n)
{
TextBox txtBoxMoreSolution = new TextBox();
Label lblMoreSolution = new Label();
btn = new Button();
btn.Text = "add step";
btn.ID = "btn" + controlNumber;
btn.Click += new EventHandler(btn_Click);
ViewState["btnId"] = btn.ID;
Label lbl = new Label();
lbl.Text = "Soltuion" + (controlNumber + 1);
lbl.ID = "moreSolution" + (controlNumber + 1);
lbl.Font.Size = 20;
lbl.Font.Underline = true;
lbl.Font.Bold = true;
txtBoxMoreSolution.ID = "txtBoxMoreSolution" + controlNumber;
txtBoxMoreSolution.TextMode = TextBoxMode.MultiLine;
txtBoxMoreSolution.Width = 470;
txtBoxMoreSolution.Height = 50;
lblMoreSolution.ID = "lblMoreSolution" + controlNumber;
lblMoreSolution.Text = "Step " + n + ": ";
lblMoreSolution.Width = 200;
plcAddMoreSolution.Controls.Add(lbl);
plcAddMoreSolution.Controls.Add(lblMoreSolution);
plcAddMoreSolution.Controls.Add(txtBoxMoreSolution);
plcAddMoreSolution.Controls.Add(btn);
}
private void btn_Click(object sender, EventArgs e)
{
TotalNumberSolStepAdded++;
Number++;
string str = (string)ViewState["btnId"];
if (str != null)
{
string resultString = Regex.Match(str, #"\d+").Value;
a = int.Parse(resultString);
table = (DataTable)ViewState["t"];
if (table == null)
{
DataTable table1 = new DataTable();
table1.Columns.Add("count", typeof(int));
dr = table1.NewRow();
table1.Rows.Add(dr);
table1.Rows[a - 1]["count"] = Number;
table1.AcceptChanges();
ViewState["t"] = table1;
}
else
{
if (a != table.Rows.Count)
{
dr = table.NewRow();
table.Rows.Add(dr);
}
table.Rows[a - 1]["count"] = Number;
table.AcceptChanges();
ViewState["t"] = table;
}
}
AddMoreStepControls(TotalNumberSolStepAdded, Number);
}
protected int TotalNumberSolStepAdded
{
get { return (int)(ViewState["TotalNumberSolStepAdded"] ?? 0); }
set { ViewState["TotalNumberSolStepAdded"] = value; }
}
protected int Number
{
get { return (int)(ViewState["Number"] ?? 0); }
set { ViewState["Number"] = value; }
}
private void AddMoreStepControls(int controlNumber, int counter)
{
TextBox txtBoxMoreStepSolution = new TextBox();
Label lblMoreStepSolution = new Label();
txtBoxMoreStepSolution.ID = "txtBoxMoreStepSolution" + controlNumber;
txtBoxMoreStepSolution.TextMode = TextBoxMode.MultiLine;
txtBoxMoreStepSolution.Width = 470;
txtBoxMoreStepSolution.Height = 50;
lblMoreStepSolution.ID = "lblMoreStepSolution" + controlNumber;
lblMoreStepSolution.Text = "Step " + (counter + 1) + ": ";
lblMoreStepSolution.Width = 200;
plcAddMoreSolution.Controls.Add(lblMoreStepSolution);
plcAddMoreSolution.Controls.Add(txtBoxMoreStepSolution);
}
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)