Vivek Kumar Vishwas

Vivek Kumar Vishwas

  • NA
  • 115
  • 54.9k

How to Create Text Box Dynamically in asp.net c#

Nov 7 2017 1:48 AM
Hello,
 
My Requirement is as following :
  • Creatingtext box Dynamically
  • Inserting data from generated textbox value into Database
  • Populating the line-chart from database
  1. // aspx//  
  2. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="_Default" %>  
  3. <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>  
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7. <title></title>  
  8. <style type="text/css">  
  9. body  
  10. {  
  11. font-family: Arial;  
  12. font-size: 10pt;  
  13. }  
  14. input[type=text]  
  15. {  
  16. margin-bottom: 10pt;  
  17. }  
  18. </style>  
  19. <%--date picker--%>  
  20. <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">  
  21. <link rel="stylesheet" href="/resources/demos/style.css">  
  22. <script src="https://code.jquery.com/jquery-1.12.4.js"></script>  
  23. <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>  
  24. <script>  
  25. $(function () {  
  26. $("#datepicker").datepicker();  
  27. });  
  28. </script>  
  29. <script>  
  30. $(function () {  
  31. $("#datepicker2").datepicker();  
  32. });  
  33. </script>  
  34. <%--end--%>  
  35. </head>  
  36. <body>  
  37. <form id="form1" runat="server">  
  38. <div>  
  39. <span class="style1"><strong>How to display Static LineChart on ASP.NET Webpage</strong></span>  
  40. <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">  
  41. </asp:ToolkitScriptManager>  
  42. <%--<asp:LineChart ID="LineChart11" runat="server" ChartWidth="450" ChartHeight="300"  
  43. ChartType="Basic" ChartTitle="Earings in Different Years" CategoriesAxis="1,2,3,4,5,6,7,8"  
  44. ChartTitleColor="#0E426C" CategoryAxisLineColor="#D08AD9" ValueAxisLineColor="#D08AD9"  
  45. BaseLineColor="#A156AB">  
  46. <Series>  
  47. <asp:LineChartSeries Name="N K techology" LineColor="#CC66FF" Data="80, 7, 600, 150,40, 300,120,100" />  
  48. <asp:LineChartSeries Name="Kiran" LineColor="#3399FF"  
  49. Data="9900, 4000, 11600, 9700,3200, 8600,6900,9950" />  
  50. <asp:LineChartSeries Name="sachin" LineColor="#FF0066"  
  51. Data="12000, 17000, 1500, 8400,9600, 11900,17600,12030" />  
  52. </Series>  
  53. </asp:LineChart>--%>  
  54. <asp:LineChart ID="LineChart1" runat="server" ChartHeight="300" ChartWidth = "450"  
  55. ChartType="Basic" ChartTitleColor="#000" Visible = "false"  
  56. CategoryAxisLineColor="#000" ValueAxisLineColor="#000" BaseLineColor="#c1c1c1">  
  57. </asp:LineChart>  
  58. <br />  
  59. <p>  
  60. Date 1:  
  61. <input type="text" id="datepicker" runat="server" />  
  62. </p>  
  63. <p>  
  64. Date 2:  
  65. <input type="text" id="datepicker2" runat="server" />  
  66. </p>  
  67. <asp:Button ID="bnt" runat="server" OnClick="bnt_Click" Text="Get Date" />  
  68. </div>  
  69. <asp:Panel ID="pnlTextBoxes" runat="server">  
  70. </asp:Panel>  
  71. <hr />  
  72. <asp:Button ID="btnAdd" runat="server" Text="Add New" OnClick="AddTextBox" />  
  73. <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="Save" />  
  74. <asp:Button ID="GenerateChart" runat="server" Text="Populate Chart"  
  75. onclick="GenerateChart_Click" />  
  76. </form>  
  77. </body>  
  78. </html>  
------Codebehind c# ----------
  1. using System;  
  2. using System.Web;  
  3. using System.Web.Security;  
  4. using System.Web.UI;  
  5. using System.Web.UI.WebControls;  
  6. using System.Linq;  
  7. using System.Collections.Generic;  
  8. using System.Data;  
  9. using System.Configuration;  
  10. using System.Data.SqlClient;  
  11. public partial class _Default : System.Web.UI.Page  
  12. {  
  13. int totaldays = 0;  
  14. protected void Page_PreInit(object sender, EventArgs e)  
  15. {  
  16. List keys = Request.Form.AllKeys.Where(key => key.Contains("txtDynamic")).ToList();  
  17. int i = 1;  
  18. foreach (string key in keys)  
  19. {  
  20. this.CreateTextBox("txtDynamic" + i);  
  21. i++;  
  22. }  
  23. }  
  24. protected void AddTextBox(object sender, EventArgs e)  
  25. {  
  26. int index = pnlTextBoxes.Controls.OfType().ToList().Count + 1;  
  27. this.CreateTextBox("txtDynamic" + index);  
  28. }  
  29. private void CreateTextBox(string id)  
  30. {  
  31. //TextBox txt = new TextBox();  
  32. //txt.ID = id;  
  33. //pnlTextBoxes.Controls.Add(txt);  
  34. //Literal lt = new Literal();  
  35. //lt.Text = "  
  36. ";  
  37. //pnlTextBoxes.Controls.Add(lt);  
  38. for (int i = 0; i < totaldays; i++) //specifying the condition in for loop for creating no. of textboxes  
  39. {  
  40. //TextBox tb = new TextBox(); //Create the object of TexBox Class  
  41. //tb.ID = i.ToString(); // assign the loop value to textbox object for dynamically adding Textbox ID  
  42. //Form.Controls.Add(tb); // adding the controls  
  43. TextBox txt = new TextBox();  
  44. txt.ID = id;  
  45. pnlTextBoxes.Controls.Add(txt);  
  46. Literal lt = new Literal();  
  47. lt.Text = "  
  48. ";  
  49. pnlTextBoxes.Controls.Add(lt);  
  50. }  
  51. }  
  52. protected void Save(object sender, EventArgs e)  
  53. {  
  54. foreach (TextBox textBox in pnlTextBoxes.Controls.OfType())  
  55. {  
  56. string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;  
  57. using (SqlConnection con = new SqlConnection(constr))  
  58. {  
  59. //for (int i = 0; i < totaldays; i++) //specifying the condition in for loop for creating no. of textboxes  
  60. //{  
  61. using (SqlCommand cmd = new SqlCommand("INSERT INTO chart VALUES(@DT,@Value)"))  
  62. {  
  63. cmd.Connection = con;  
  64. cmd.Parameters.AddWithValue("@DT", textBox.Text);  
  65. cmd.Parameters.AddWithValue("@value", textBox.Text);  
  66. con.Open();  
  67. cmd.ExecuteNonQuery();  
  68. con.Close();  
  69. Response.Write("<!-- Inject Script Filtered -->");  
  70. }  
  71. // }  
  72. }  
  73. }  
  74. }  
  75. //  
  76. private static DataTable GetData(string query)  
  77. {  
  78. DataTable dt = new DataTable();  
  79. string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;  
  80. using (SqlConnection con = new SqlConnection(constr))  
  81. {  
  82. using (SqlCommand cmd = new SqlCommand(query))  
  83. {  
  84. using (SqlDataAdapter sda = new SqlDataAdapter())  
  85. {  
  86. cmd.CommandType = CommandType.Text;  
  87. cmd.Connection = con;  
  88. sda.SelectCommand = cmd;  
  89. sda.Fill(dt);  
  90. }  
  91. }  
  92. return dt;  
  93. }  
  94. }  
  95. protected void GenerateChart_Click(object sender, EventArgs e)  
  96. {  
  97. string query = string.Format("select * from chart");  
  98. DataTable dt = GetData(query);  
  99. string[] x = new string[dt.Rows.Count];  
  100. decimal[] y = new decimal[dt.Rows.Count];  
  101. for (int i = 0; i < dt.Rows.Count; i++)  
  102. {  
  103. x[i] = dt.Rows[i][0].ToString();  
  104. y[i] = Convert.ToInt32(dt.Rows[i][1]);  
  105. }  
  106. LineChart1.Series.Add(new AjaxControlToolkit.LineChartSeries { Data = y });  
  107. LineChart1.CategoriesAxis = string.Join(",", x);  
  108. // LineChart1.ChartTitle = string.Format("{0} Order Distribution", ddlCountries.SelectedItem.Value);  
  109. if (x.Length > 3)  
  110. {  
  111. LineChart1.ChartWidth = (x.Length * 75).ToString();  
  112. }  
  113. LineChart1.Visible = true;  
  114. }  
  115. public void datediff()  
  116. {  
  117. if (datepicker2.Value != "" && datepicker.Value != "")  
  118. {  
  119. //Storing input Dates  
  120. DateTime FromYear = Convert.ToDateTime(datepicker.Value);  
  121. DateTime ToYear = Convert.ToDateTime(datepicker2.Value);  
  122. //Creating object of TimeSpan Class  
  123. TimeSpan objTimeSpan = ToYear - FromYear;  
  124. //years  
  125. int Years = ToYear.Year - FromYear.Year;  
  126. //months  
  127. int month = ToYear.Month - FromYear.Month;  
  128. //TotalDays  
  129. double Days = Convert.ToDouble(objTimeSpan.TotalDays);  
  130. totaldays = Convert.ToInt32(Days);  
  131. Response.Write("<!-- Inject Script Filtered -->");  
  132. ////Total Months  
  133. //int TotalMonths = (Years * 12) + month;  
  134. ////Total Hours  
  135. //double TotalHours = objTimeSpan.TotalHours;  
  136. ////Total Minutes  
  137. //double TotalMinutes = objTimeSpan.TotalMinutes;  
  138. ////Total Seconds  
  139. //double TotalSeconds = objTimeSpan.TotalSeconds;  
  140. ////Total Mile Seconds  
  141. //double TotalMileSeconds = objTimeSpan.TotalMilliseconds;  
  142. }  
  143. }  
  144. protected void bnt_Click(object sender, EventArgs e)  
  145. {  
  146. datediff();  
  147. int index = pnlTextBoxes.Controls.OfType().ToList().Count + 1;  
  148. this.CreateTextBox("txtDynamic" + index);  
  149. }  
  150. }

Answers (4)