Introduction
This article explains how to create dynamic controls from code-behind and validate them through JavaScript.
Using the code
On page load the controls will be loaded dynamically from code-behind. On submit click event, validation is performed using JavaScript.
In case of failure, error messages are displayed. In case of success, submit click event is performed.
ASPX code:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="DynamicControls.aspx.cs"
Inherits="Practice.Aspx.DynamicControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.red
{
color: Red;
}
</style>
<script type="text/javascript">
function fnValidate() {
var txt = document.getElementById("txtSample");
var drpGender = document.getElementById("drpGender");
var x = document.getElementById('ErrorMessage');
x.innerHTML = "";
if (drpGender.value == "Select") {
x.innerHTML = "Please Select Gender<br>";
}
if (txt.value == "") {
x.innerHTML += "Enter Name in Textbox";
}
if (x.innerHTML != "") {
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="ErrorMessage" runat="server" class="red">
</div>
<div id="GenerateControls" runat="server">
</div>
<div id="SubmitButton" runat="server">
</div>
</form>
</body>
</html>
Code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Practice.Aspx
{
public partial class DynamicControls : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TextBox txtSample = new TextBox();
txtSample.ID = "txtSample";
GenerateControls.Controls.Add(txtSample);
GenerateControls.Controls.Add(new LiteralControl("<br />"));
DropDownList drp = new DropDownList();
drp.ID = "drpGender";
drp.Items.Add("Select");
drp.Items.Add("Male");
drp.Items.Add("Female");
GenerateControls.Controls.Add(drp);
Button submit = new Button();
submit.ID = "btnSubmit";
submit.Text = "Submit";
submit.Click += new EventHandler(btnSubmit_Click);
SubmitButton.Controls.Add(submit);
SubmitButton.Attributes.Add("onclick",
"javascript:return fnValidate()");
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
TextBox txtSample = (TextBox)GenerateControls.FindControl("txtSample");
DropDownList drpGender =
(DropDownList)GenerateControls.FindControl("drpGender");
String[] str = new String[10];
str[0] = txtSample.Text;
str[1] = drpGender.SelectedItem.Text;
}
}
}