Asp.net MVC CRUD Operation


using MvcLastAttempt.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;

namespace MvcLastAttempt.Controllers
{
public class HelpController : Controller
{
//
// GET: /Help/
private MarutiEntities db = new MarutiEntities();
public ActionResult Index()
{
var products = db.Products.Include(p => p.Category);
return View(db.Products.ToList());
}
public ActionResult Create()
{
ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName");
return View();
}

[HttpPost]
public ActionResult Create(Product product)
{
if (ModelState.IsValid)
{
db.Products.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}

ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", product.CategoryID);
return View(product);
}

public ActionResult Edit(int id = 0)
{
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", product.CategoryID);
return View(product);
}

//
// POST: /Main/Edit/5

[HttpPost]
public ActionResult Edit(Product product)
{
if (ModelState.IsValid)
{
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", product.CategoryID);
return View(product);
}

public ActionResult Delete(int id = 0)
{
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
return View(product);
}

//
// POST: /Main/Delete/5

[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Product product = db.Products.Find(id);
db.Products.Remove(product);
db.SaveChanges();
return RedirectToAction("Index");
}

protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}

}
}

VIEW


@model MvcLastAttempt.Models.Product

@{
Layout = null;
}

<script src=''>

Create

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

Product

@Html.LabelFor(model => model.CategoryID)
@Html.DropDownList("CategoryID", String.Empty)
@Html.ValidationMessageFor(model => model.CategoryID)
@Html.LabelFor(model => model.ProductName)
@Html.EditorFor(model => model.ProductName)
@Html.ValidationMessageFor(model => model.ProductName)
@Html.LabelFor(model => model.Description)
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description)

}

@Html.ActionLink("Back to List", "Index")

--Edit
@model MvcLastAttempt.Models.Product

@{
Layout = null;
}

Edit

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

Product

@Html.HiddenFor(model => model.ProductID)

@Html.LabelFor(model => model.CategoryID)
@Html.DropDownList("CategoryID", "--Select--")
@Html.ValidationMessageFor(model => model.CategoryID)
@Html.LabelFor(model => model.ProductName)
@Html.EditorFor(model => model.ProductName)
@Html.ValidationMessageFor(model => model.ProductName)
@Html.LabelFor(model => model.Description)
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description)

}

@Html.ActionLink("Back to List", "Index")

--Delete
@model MvcLastAttempt.Models.Product

@{
Layout = null;
}

Delete

Are you sure you want to delete this?

Product

@Html.DisplayNameFor(model => model.CategoryID)
@Html.DisplayFor(model => model.CategoryID)
@Html.DisplayNameFor(model => model.ProductName)
@Html.DisplayFor(model => model.ProductName)
@Html.DisplayNameFor(model => model.Description)
@Html.DisplayFor(model => model.Description)

@using (Html.BeginForm()) {

|
@Html.ActionLink("Back to List", "Index")

}

--List

@model IEnumerable

@{
Layout = null;
}

Index

@Html.ActionLink("Create New", "Create")

@foreach (var item in Model) {

}

@Html.DisplayNameFor(model => model.Category.CategoryName) @Html.DisplayNameFor(model => model.ProductName) @Html.DisplayNameFor(model => model.Description)
@Html.DisplayFor(modelItem => item.Category.CategoryName) @Html.DisplayFor(modelItem => item.ProductName) @Html.DisplayFor(modelItem => item.Description) @Html.ActionLink("Edit", "Edit", new { id=item.ProductID }) |
@Html.ActionLink("Details", "Details", new { id=item.ProductID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ProductID })

Asp.net MVC3 Paging ,Sorting and Filtering

Controller:

using MvcLastAttempt.Models;
using PagedList;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcLastAttempt.Controllers
{
public class ProductController : Controller
{
//
// GET: /Product/
MarutiEntities _db;

public ProductController()
{
_db = new MarutiEntities();
}

public ActionResult Index(string sortOrder, string CurrentSort, int? page, string searchString)
{
int pageSize = 10;
int pageIndex = 1;
pageIndex = page.HasValue ? Convert.ToInt32(page) : 1;

ViewBag.CurrentSort = sortOrder;

sortOrder = String.IsNullOrEmpty(sortOrder) ? "ProductID" : sortOrder;

IPagedList<Product> products = null;

switch (sortOrder)
{
case "ProductID":
if (sortOrder.Equals(CurrentSort))
products = _db.Products.OrderByDescending
(m => m.ProductID).ToPagedList(pageIndex, pageSize);
else
products = _db.Products.OrderBy
(m => m.ProductID).ToPagedList(pageIndex, pageSize);
break;
case "ProductName":
if (sortOrder.Equals(CurrentSort))
products = _db.Products.OrderByDescending
(m => m.ProductName).ToPagedList(pageIndex, pageSize);
else
products = _db.Products.OrderBy
(m => m.ProductName).ToPagedList(pageIndex, pageSize);
break;
case "Description":
if (sortOrder.Equals(CurrentSort))
products = _db.Products.OrderByDescending
(m => m.Description).ToPagedList(pageIndex, pageSize);
else
products = _db.Products.OrderBy
(m => m.Description).ToPagedList(pageIndex, pageSize);
break;
// Add sorting statements for other columns

case "Default":
products = _db.Products.OrderBy
(m => m.ProductID).ToPagedList(pageIndex, pageSize);
break;
}
if (!String.IsNullOrEmpty(searchString))
{
// products = _db.Products.Where(s => s.ProductName.Contains(searchString) || s.ProductName.Contains(searchString));

}
return View(products);
}

}
}

View:

@model PagedList.IPagedList<MvcLastAttempt.Models.Product>

@using PagedList.Mvc;
@{
ViewBag.Title = "Product List";
Layout = null;
}

<h2>Product List</h2>
@using (Html.BeginForm("Index", "Product", FormMethod.Get))
{
<p>
Find by name: @Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
<input type="submit" value="Search" />
</p>
}
@using (Html.BeginForm())
{
<table>
<tr>
<th style="border: 2px solid black; text-align: center; width: 12%">
@Html.ActionLink("Product ID", "Index",
new { sortOrder = "ProductID", CurrentSort = ViewBag.CurrentSort ,currentFilter = ViewBag.CurrentFilter })
</th>
<th style="border: 2px solid black; text-align: center; width: 25%">
@Html.ActionLink("Product Name", "Index",
new { sortOrder = "ProductName", CurrentSort = ViewBag.CurrentSort,currentFilter = ViewBag.CurrentFilter })
</th>
<th style="border: 2px solid black; text-align: center; width: 15%;">
@Html.ActionLink("Description", "Index",
new { sortOrder = "Description", CurrentSort = ViewBag.CurrentSort ,currentFilter = ViewBag.CurrentFilter })
</th>

</tr>
@foreach (var item in Model)
{
<tr>
<td style="border: 2px solid black; text-align: center; word-wrap: break-word;">
@Html.DisplayFor(modelItem => item.ProductID)
</td>
<td style="border: 2px solid black; text-align: center; word-wrap: break-word;">
@Html.DisplayFor(modelItem => item.ProductName)
</td>
<td style="border: 2px solid black; text-align: center; word-wrap: break-word;">
@Html.DisplayFor(modelItem => item.Description)
</td>

</tr>
}
</table>
<br />
<div id='Paging' style="text-align: center">
Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
of @Model.PageCount

@Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
</div>
}

 

 

Cascading DropDownlist in MVC4

Controller: Read more of this post

Enable ASP.NET (IIS 8.0)

To enable ASP.NET on a server running Windows Server 2003 by using the Configure Your Server wizard

1. Click Start, and then click Manage Your Server.
2. In the Manage Your Server window, click Add or remove a role.
3. In the Configure Your Server wizard, click Next.
4. In the Server Role dialog box, click Application Server (IIS, ASP.NET) and then click Next.
5. In the Application Server Options dialog box, select the Enable ASP.NET check box.
6. Click Next, and then click Next again.
7. If you are prompted to do so, insert your Windows Server 2003 installation CD in the CD-ROM drive, and then click Next.
8. When the installation is complete, click Finish.

To enable ASP.NET on a server running Windows Server 2003 by using Add or Remove Programs

1. In Control Panel, click Add or Remove Programs.
2. Click Add/Remove Windows Components.
3. In the Components box in the Windows Components Wizard, select the Application Server check box, and then click Details.
4. In the Application Server dialog box, select the ASP.NET check box, and then click OK.
5. In the Windows Components Wizard, click Next to begin installing ASP.NET.
6. When the Windows Components Wizard has finished configuring Windows Server 2003, click Finish.

Javascript Calendar

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Hope.aspx.cs” Inherits=”Hope” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title>Untitled Page</title>

<script language=”JavaScript”>
<!– Original: Nick Korosi (nfk2000@hotmail.com) –>

<!– This script and many more are available free online at –>
<!– The JavaScript Source!! http://javascript.internet.com –>

<!– Begin
var dDate = new Date();
var dCurMonth = dDate.getMonth();
var dCurDayOfMonth = dDate.getDate();
var dCurYear = dDate.getFullYear();
var objPrevElement = new Object();

function fToggleColor(myElement) {
var toggleColor = “#ff0000”;
if (myElement.id == “calDateText”) {
if (myElement.color == toggleColor) {
myElement.color = “”;
} else {
myElement.color = toggleColor;
}
} else if (myElement.id == “calCell”) {
for (var i in myElement.children) {
if (myElement.children[i].id == “calDateText”) {
if (myElement.children[i].color == toggleColor) {
myElement.children[i].color = “”;
} else {
myElement.children[i].color = toggleColor;
}
}
}
}
}
function fSetSelectedDay(myElement){
if (myElement.id == “calCell”) {
if (!isNaN(parseInt(myElement.children[“calDateText”].innerText))) {
myElement.bgColor = “#c0c0c0”;
objPrevElement.bgColor = “”;
document.all.calSelectedDate.value = parseInt(myElement.children[“calDateText”].innerText);
objPrevElement = myElement;
}
}
}
function fGetDaysInMonth(iMonth, iYear) {
var dPrevDate = new Date(iYear, iMonth, 0);
return dPrevDate.getDate();
}
function fBuildCal(iYear, iMonth, iDayStyle) {
var aMonth = new Array();
aMonth[0] = new Array(7);
aMonth[1] = new Array(7);
aMonth[2] = new Array(7);
aMonth[3] = new Array(7);
aMonth[4] = new Array(7);
aMonth[5] = new Array(7);
aMonth[6] = new Array(7);
var dCalDate = new Date(iYear, iMonth-1, 1);
var iDayOfFirst = dCalDate.getDay();
var iDaysInMonth = fGetDaysInMonth(iMonth, iYear);
var iVarDate = 1;
var i, d, w;
if (iDayStyle == 2) {
aMonth[0][0] = “Sunday”;
aMonth[0][1] = “Monday”;
aMonth[0][2] = “Tuesday”;
aMonth[0][3] = “Wednesday”;
aMonth[0][4] = “Thursday”;
aMonth[0][5] = “Friday”;
aMonth[0][6] = “Saturday”;
} else if (iDayStyle == 1) {
aMonth[0][0] = “Sun”;
aMonth[0][1] = “Mon”;
aMonth[0][2] = “Tue”;
aMonth[0][3] = “Wed”;
aMonth[0][4] = “Thu”;
aMonth[0][5] = “Fri”;
aMonth[0][6] = “Sat”;
} else {
aMonth[0][0] = “Su”;
aMonth[0][1] = “Mo”;
aMonth[0][2] = “Tu”;
aMonth[0][3] = “We”;
aMonth[0][4] = “Th”;
aMonth[0][5] = “Fr”;
aMonth[0][6] = “Sa”;
}
for (d = iDayOfFirst; d < 7; d++) {
aMonth[1][d] = iVarDate;
iVarDate++;
}
for (w = 2; w < 7; w++) {
for (d = 0; d < 7; d++) {
if (iVarDate <= iDaysInMonth) {
aMonth[w][d] = iVarDate;
iVarDate++;
}
}
}
return aMonth;
}
function fDrawCal(iYear, iMonth, iCellWidth, iCellHeight, sDateTextSize, sDateTextWeight, iDayStyle) {
var myMonth;
myMonth = fBuildCal(iYear, iMonth, iDayStyle);
document.write(“<table border=’1′>”)
document.write(“<tr>”);
document.write(“<td align=’center’ style=’FONT-FAMILY:Arial;FONT-SIZE:12px;FONT-WEIGHT: bold’>” + myMonth[0][0] + “</td>”);
document.write(“<td align=’center’ style=’FONT-FAMILY:Arial;FONT-SIZE:12px;FONT-WEIGHT: bold’>” + myMonth[0][1] + “</td>”);
document.write(“<td align=’center’ style=’FONT-FAMILY:Arial;FONT-SIZE:12px;FONT-WEIGHT: bold’>” + myMonth[0][2] + “</td>”);
document.write(“<td align=’center’ style=’FONT-FAMILY:Arial;FONT-SIZE:12px;FONT-WEIGHT: bold’>” + myMonth[0][3] + “</td>”);
document.write(“<td align=’center’ style=’FONT-FAMILY:Arial;FONT-SIZE:12px;FONT-WEIGHT: bold’>” + myMonth[0][4] + “</td>”);
document.write(“<td align=’center’ style=’FONT-FAMILY:Arial;FONT-SIZE:12px;FONT-WEIGHT: bold’>” + myMonth[0][5] + “</td>”);
document.write(“<td align=’center’ style=’FONT-FAMILY:Arial;FONT-SIZE:12px;FONT-WEIGHT: bold’>” + myMonth[0][6] + “</td>”);
document.write(“</tr>”);
for (w = 1; w < 7; w++) {
document.write(“<tr>”)
for (d = 0; d < 7; d++) {
document.write(“<td align=’left’ valign=’top’ width='” + iCellWidth + “‘ height='” + iCellHeight + “‘ id=calCell style=’CURSOR:Hand’ onMouseOver=’fToggleColor(this)’ onMouseOut=’fToggleColor(this)’ onclick=fSetSelectedDay(this)>”);
if (!isNaN(myMonth[w][d])) {
document.write(“<font id=calDateText onMouseOver=’fToggleColor(this)’ style=’CURSOR:Hand;FONT-FAMILY:Arial;FONT-SIZE:” + sDateTextSize + “;FONT-WEIGHT:” + sDateTextWeight + “‘ onMouseOut=’fToggleColor(this)’ onclick=fSetSelectedDay(this)>” + myMonth[w][d] + “</font>”);
} else {
document.write(“<font id=calDateText onMouseOver=’fToggleColor(this)’ style=’CURSOR:Hand;FONT-FAMILY:Arial;FONT-SIZE:” + sDateTextSize + “;FONT-WEIGHT:” + sDateTextWeight + “‘ onMouseOut=’fToggleColor(this)’ onclick=fSetSelectedDay(this)> </font>”);
}
document.write(“</td>”)
}
document.write(“</tr>”);
}
document.write(“</table>”)
}
function fUpdateCal(iYear, iMonth) {
myMonth = fBuildCal(iYear, iMonth);
objPrevElement.bgColor = “”;
document.all.calSelectedDate.value = “”;
for (w = 1; w < 7; w++) {
for (d = 0; d < 7; d++) {
if (!isNaN(myMonth[w][d])) {
calDateText[((7*w)+d)-7].innerText = myMonth[w][d];
} else {
calDateText[((7*w)+d)-7].innerText = ” “;
}
}
}
}
// End –>
</script>

</head>
<body>

<script language=”JavaScript” for=”window” event=”onload”>
<!– Begin
var dCurDate = new Date();
frmCalendarSample.tbSelMonth.options[dCurDate.getMonth()].selected = true;
for (i = 0; i < frmCalendarSample.tbSelYear.length; i++)
if (frmCalendarSample.tbSelYear.options[i].value == dCurDate.getFullYear())
frmCalendarSample.tbSelYear.options[i].selected = true;
// End –>
</script>

<form name=”frmCalendarSample” method=”post” action=””>
<input type=”hidden” name=”calSelectedDate” value=””>
<table border=”1″>
<tr>
<td>
<select name=”tbSelMonth” onchange=’fUpdateCal(frmCalendarSample.tbSelYear.value, frmCalendarSample.tbSelMonth.value)’>
<option value=”1″>January</option>
<option value=”2″>February</option>
<option value=”3″>March</option>
<option value=”4″>April</option>
<option value=”5″>May</option>
<option value=”6″>June</option>
<option value=”7″>July</option>
<option value=”8″>August</option>
<option value=”9″>September</option>
<option value=”10″>October</option>
<option value=”11″>November</option>
<option value=”12″>December</option>
</select>
<select name=”tbSelYear” onchange=’fUpdateCal(frmCalendarSample.tbSelYear.value, frmCalendarSample.tbSelMonth.value)’>
<option value=”1998″>1998</option>
<option value=”1999″>1999</option>
<option value=”2000″>2000</option>
<option value=”2001″>2001</option>
<option value=”2002″>2002</option>
<option value=”2003″>2003</option>
<option value=”2004″>2004</option>
</select>
</td>
</tr>
<tr>
<td>

<script language=”JavaScript”>
var dCurDate = new Date();
fDrawCal(dCurDate.getFullYear(), dCurDate.getMonth()+1, 30, 30, “12px”, “bold”, 1);
</script>

</td>
</tr>
</table>
</form>
</body>
</html>

Filter Sunday from Asp.net Calendar Control

DEFAULT.ASPX

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”cal.aspx.cs” Inherits=”cal” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:Calendar ID=”cal1″ runat=”server” />
<br />
<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”true”>
</asp:GridView>

<asp:Label ID=”lbl1″ runat=”Server” ></asp:Label>
<asp:Label ID=”lbl2″ runat=”Server” ></asp:Label>
<asp:Button ID=”btn1″ runat=”Server” Text=”select Date” OnClick=”btn1_click” />
</div>
</form>
</body>
</html>

Read more of this post

Filter Sunday from Asp.net Calendar Control

Untitled Page

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = getSundays();
GridView1.DataBind();
}

}

public static List getSundays()
{

List lstSundays = new List();

int intMonth = DateTime.Now.Month;

int intYear = DateTime.Now.Year;

int intDaysThisMonth = DateTime.DaysInMonth(intYear, intMonth);

DateTime oBeginnngOfThisMonth = new DateTime(intYear, intMonth, 1);

for (int i = 1; i < intDaysThisMonth + 1; i++)
{

if (oBeginnngOfThisMonth.AddDays(i).DayOfWeek == DayOfWeek.Sunday)
{
int lal = oBeginnngOfThisMonth.Date.Day;
lstSundays.Add(new DateTime(intYear, intMonth,oBeginnngOfThisMonth.AddDays(i).Date.Day));

//lstSundays.Add(new DateTime(2012, 1, 1));
}

}

return lstSundays;

}

Adding Dynamic Rows in GridView with TextBox and DropDownList

Default.aspx

 <div>
        <asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
                <asp:TemplateField HeaderText="Header 1">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Header 2">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Header 3">
                    <ItemTemplate>
                        <asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
                            <asp:ListItem Value="-1">Select</asp:ListItem>
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Header 4">
                    <ItemTemplate>
                        <asp:DropDownList ID="DropDownList2" runat="server" AppendDataBoundItems="true">
                            <asp:ListItem Value="-1">Select</asp:ListItem>
                        </asp:DropDownList>
                    </ItemTemplate>
                    <FooterStyle HorizontalAlign="Right" />
                    <FooterTemplate>
                        <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
                    </FooterTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>

Default.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class DynamicTextDDL : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            SetInitialRow();
        }

    }
    private ArrayList GetDummyData()
    {

        ArrayList arr = new ArrayList();

        arr.Add(new ListItem("Item1", "1"));
        arr.Add(new ListItem("Item2", "2"));
        arr.Add(new ListItem("Item3", "3"));
        arr.Add(new ListItem("Item4", "4"));
        arr.Add(new ListItem("Item5", "5"));

        return arr;
    }

    private void FillDropDownList(DropDownList ddl)
    {
        ArrayList arr = GetDummyData();

        foreach (ListItem item in arr)
        {
            ddl.Items.Add(item);
        }
    }

    private void SetInitialRow()
    {

        DataTable dt = new DataTable();
        DataRow dr = null;

        dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
        dt.Columns.Add(new DataColumn("Column1", typeof(string)));//for TextBox value
        dt.Columns.Add(new DataColumn("Column2", typeof(string)));//for TextBox value
        dt.Columns.Add(new DataColumn("Column3", typeof(string)));//for DropDownList selected item
        dt.Columns.Add(new DataColumn("Column4", typeof(string)));//for DropDownList selected item

        dr = dt.NewRow();
        dr["RowNumber"] = 1;
        dr["Column1"] = string.Empty;
        dr["Column2"] = string.Empty;
        dt.Rows.Add(dr);

        //Store the DataTable in ViewState for future reference

        ViewState["CurrentTable"] = dt;

        //Bind the Gridview
        Gridview1.DataSource = dt;
        Gridview1.DataBind();

        //After binding the gridview, we can then extract and fill the DropDownList with Data

        DropDownList ddl1 = (DropDownList)Gridview1.Rows[0].Cells[3].FindControl("DropDownList1");
        DropDownList ddl2 = (DropDownList)Gridview1.Rows[0].Cells[4].FindControl("DropDownList2");
        FillDropDownList(ddl1);
        FillDropDownList(ddl2);
    }

    private void AddNewRowToGrid()
    {

        if (ViewState["CurrentTable"] != null)
        {

            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;

            if (dtCurrentTable.Rows.Count > 0)
            {
                drCurrentRow = dtCurrentTable.NewRow();
                drCurrentRow["RowNumber"] = dtCurrentTable.Rows.Count + 1;

                //add new row to DataTable
                dtCurrentTable.Rows.Add(drCurrentRow);
                //Store the current data to ViewState for future reference

                ViewState["CurrentTable"] = dtCurrentTable;


                for (int i = 0; i < dtCurrentTable.Rows.Count - 1; i++)
                {

                    //extract the TextBox values

                    TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1");
                    TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2");

                    dtCurrentTable.Rows[i]["Column1"] = box1.Text;
                    dtCurrentTable.Rows[i]["Column2"] = box2.Text;

                    //extract the DropDownList Selected Items

                    DropDownList ddl1 = (DropDownList)Gridview1.Rows[i].Cells[3].FindControl("DropDownList1");
                    DropDownList ddl2 = (DropDownList)Gridview1.Rows[i].Cells[4].FindControl("DropDownList2");

                    // Update the DataRow with the DDL Selected Items

                    dtCurrentTable.Rows[i]["Column3"] = ddl1.SelectedItem.Text;
                    dtCurrentTable.Rows[i]["Column4"] = ddl2.SelectedItem.Text;

                }

                //Rebind the Grid with the current data to reflect changes
                Gridview1.DataSource = dtCurrentTable;
                Gridview1.DataBind();
            }
        }
        else
        {
            Response.Write("ViewState is null");

        }
        //Set Previous Data on Postbacks
        SetPreviousData();
    }

    private void SetPreviousData()
    {

        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {

            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {

                for (int i = 0; i < dt.Rows.Count; i++)
                {

                    TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1");
                    TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2");

                    DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1");
                    DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[4].FindControl("DropDownList2");

                    //Fill the DropDownList with Data
                    FillDropDownList(ddl1);
                    FillDropDownList(ddl2);

                    if (i < dt.Rows.Count - 1)
                    {

                        //Assign the value from DataTable to the TextBox
                        box1.Text = dt.Rows[i]["Column1"].ToString();
                        box2.Text = dt.Rows[i]["Column2"].ToString();

                        //Set the Previous Selected Items on Each DropDownList  on Postbacks
                        ddl1.ClearSelection();
                        ddl1.Items.FindByText(dt.Rows[i]["Column3"].ToString()).Selected = true;

                        ddl2.ClearSelection();
                        ddl2.Items.FindByText(dt.Rows[i]["Column4"].ToString()).Selected = true;

                    }

                    rowIndex++;
                }
            }
        }
    }



    protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        AddNewRowToGrid();
    }
}



Adding Dynamic Rows-in-gridview-with-dropdownlists.aspx

Default.aspx

<div>
        <asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
                <asp:TemplateField HeaderText="Header 1">
                    <ItemTemplate>
                        <asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
                            <asp:ListItem Value="-1">Select</asp:ListItem>
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Header 2">
                    <ItemTemplate>
                        <asp:DropDownList ID="DropDownList2" runat="server" AppendDataBoundItems="true">
                            <asp:ListItem Value="-1">Select</asp:ListItem>
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Header 3">
                    <ItemTemplate>
                        <asp:DropDownList ID="DropDownList3" runat="server" AppendDataBoundItems="true">
                            <asp:ListItem Value="-1">Select</asp:ListItem>
                        </asp:DropDownList>
                    </ItemTemplate>
                    <FooterStyle HorizontalAlign="Right" />
                    <FooterTemplate>
                        <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
                    </FooterTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
</div>

Default.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class DynamicdataTable : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {

            SetInitialRow();

        }
    }
    private ArrayList GetDummyData()
    {

        ArrayList arr = new ArrayList();

        arr.Add(new ListItem("Item1", "1"));

        arr.Add(new ListItem("Item2", "2"));

        arr.Add(new ListItem("Item3", "3"));

        arr.Add(new ListItem("Item4", "4"));

        arr.Add(new ListItem("Item5", "5"));

        return arr;

    }



    private void FillDropDownList(DropDownList ddl)
    {

        ArrayList arr = GetDummyData();

        foreach (ListItem item in arr)
        {

            ddl.Items.Add(item);

        }

    }



    private void SetInitialRow()
    {

        DataTable dt = new DataTable();

        DataRow dr = null;



        //Define the Columns

        dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));

        dt.Columns.Add(new DataColumn("Column1", typeof(string)));

        dt.Columns.Add(new DataColumn("Column2", typeof(string)));

        dt.Columns.Add(new DataColumn("Column3", typeof(string)));



        //Add a Dummy Data on Initial Load

        dr = dt.NewRow();

        dr["RowNumber"] = 1;

        dt.Rows.Add(dr);



        //Store the DataTable in ViewState

        ViewState["CurrentTable"] = dt;

        //Bind the DataTable to the Grid

        Gridview1.DataSource = dt;

        Gridview1.DataBind();



        //Extract and Fill the DropDownList with Data

        DropDownList ddl1 = (DropDownList)Gridview1.Rows[0].Cells[1].FindControl("DropDownList1");

        DropDownList ddl2 = (DropDownList)Gridview1.Rows[0].Cells[2].FindControl("DropDownList2");

        DropDownList ddl3 = (DropDownList)Gridview1.Rows[0].Cells[3].FindControl("DropDownList3");



        FillDropDownList(ddl1);

        FillDropDownList(ddl2);

        FillDropDownList(ddl3);



    }

    private void AddNewRowToGrid()
    {



        if (ViewState["CurrentTable"] != null)
        {

            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];

            DataRow drCurrentRow = null;



            if (dtCurrentTable.Rows.Count > 0)
            {

                drCurrentRow = dtCurrentTable.NewRow();

                drCurrentRow["RowNumber"] = dtCurrentTable.Rows.Count + 1;

                //add new row to DataTable

                dtCurrentTable.Rows.Add(drCurrentRow);

                //Store the current data to ViewState

                ViewState["CurrentTable"] = dtCurrentTable;



                for (int i = 0; i < dtCurrentTable.Rows.Count - 1; i++)
                {

                    //extract the DropDownList Selected Items

                    DropDownList ddl1 = (DropDownList)Gridview1.Rows[i].Cells[1].FindControl("DropDownList1");

                    DropDownList ddl2 = (DropDownList)Gridview1.Rows[i].Cells[2].FindControl("DropDownList2");

                    DropDownList ddl3 = (DropDownList)Gridview1.Rows[i].Cells[3].FindControl("DropDownList3");



                    // Update the DataRow with the DDL Selected Items

                    dtCurrentTable.Rows[i]["Column1"] = ddl1.SelectedItem.Text;

                    dtCurrentTable.Rows[i]["Column2"] = ddl2.SelectedItem.Text;

                    dtCurrentTable.Rows[i]["Column3"] = ddl3.SelectedItem.Text;



                }



                //Rebind the Grid with the current data

                Gridview1.DataSource = dtCurrentTable;

                Gridview1.DataBind();

            }

        }

        else
        {

            Response.Write("ViewState is null");

        }



        //Set Previous Data on Postbacks

        SetPreviousData();

    }



    private void SetPreviousData()
    {

        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {

            DataTable dt = (DataTable)ViewState["CurrentTable"];

            if (dt.Rows.Count > 0)
            {

                for (int i = 0; i < dt.Rows.Count; i++)
                {

                    //Set the Previous Selected Items on Each DropDownList on Postbacks

                    DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");

                    DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList2");

                    DropDownList ddl3 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList3");



                    //Fill the DropDownList with Data

                    FillDropDownList(ddl1);

                    FillDropDownList(ddl2);

                    FillDropDownList(ddl3);



                    if (i < dt.Rows.Count - 1)
                    {

                        ddl1.ClearSelection();

                        ddl1.Items.FindByText(dt.Rows[i]["Column1"].ToString()).Selected = true;



                        ddl2.ClearSelection();

                        ddl2.Items.FindByText(dt.Rows[i]["Column2"].ToString()).Selected = true;



                        ddl3.ClearSelection();

                        ddl3.Items.FindByText(dt.Rows[i]["Column3"].ToString()).Selected = true;

                    }



                    rowIndex++;

                }

            }

        }

    }





    protected void ButtonAdd_Click(object sender, EventArgs e)
    {

        AddNewRowToGrid();

    }
}

Adding Dynamic Rows in gridview-with-textboxes.aspx

Default.aspx

<div>
        <asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
                <asp:TemplateField HeaderText="Header 1">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Header 2">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Header 3">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                    </ItemTemplate>
                    <FooterStyle HorizontalAlign="Right" />
                    <FooterTemplate>
                        <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" 
                            onclick="ButtonAdd_Click" />
                    </FooterTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>

Default.aspx.cs

public partial class GVDynamicTextbox : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {

            SetInitialRow();

        }

    }
    private void SetInitialRow()
    {

        DataTable dt = new DataTable();

        DataRow dr = null;

        dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));

        dt.Columns.Add(new DataColumn("Column1", typeof(string)));

        dt.Columns.Add(new DataColumn("Column2", typeof(string)));

        dt.Columns.Add(new DataColumn("Column3", typeof(string)));

        dr = dt.NewRow();

        dr["RowNumber"] = 1;

        dr["Column1"] = string.Empty;

        dr["Column2"] = string.Empty;

        dr["Column3"] = string.Empty;

        dt.Rows.Add(dr);

        //dr = dt.NewRow();



        //Store the DataTable in ViewState

        ViewState["CurrentTable"] = dt;



        Gridview1.DataSource = dt;

        Gridview1.DataBind();

    }
    private void AddNewRowToGrid()
    {

        int rowIndex = 0;



        if (ViewState["CurrentTable"] != null)
        {

            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];

            DataRow drCurrentRow = null;

            if (dtCurrentTable.Rows.Count > 0)
            {

                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {

                    //extract the TextBox values

                    TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");

                    TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");

                    TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");



                    drCurrentRow = dtCurrentTable.NewRow();

                    drCurrentRow["RowNumber"] = i + 1;

                    drCurrentRow["Column1"] = box1.Text;

                    drCurrentRow["Column2"] = box2.Text;

                    drCurrentRow["Column3"] = box3.Text;



                    rowIndex++;

                }

                //add new row to DataTable

                dtCurrentTable.Rows.Add(drCurrentRow);

                //Store the current data to ViewState

                ViewState["CurrentTable"] = dtCurrentTable;



                //Rebind the Grid with the current data

                Gridview1.DataSource = dtCurrentTable;

                Gridview1.DataBind();

            }

        }

        else
        {

            Response.Write("ViewState is null");

        }



        //Set Previous Data on Postbacks

        SetPreviousData();

    }
    private void SetPreviousData()
    {

        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {

            DataTable dt = (DataTable)ViewState["CurrentTable"];

            if (dt.Rows.Count > 0)
            {

                for (int i = 1; i < dt.Rows.Count; i++)
                {

                    TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");

                    TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");

                    TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");



                    box1.Text = dt.Rows[i]["Column1"].ToString();

                    box2.Text = dt.Rows[i]["Column2"].ToString();

                    box3.Text = dt.Rows[i]["Column3"].ToString();



                    rowIndex++;



                }

            }

        }

    }


    protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        AddNewRowToGrid();
    }
}