About dropdown list control in gridview using c# - c#

Am using the below code to bind and show the dropdown list in grid view. But it always show the first item whether the database table have the second or third.
private void BindData1()
{
DataSet7TableAdapters.sp_getall_trv_config_masterTableAdapter TA = new DataSet7TableAdapters.sp_getall_trv_config_masterTableAdapter();
DataSet7.sp_getall_trv_config_masterDataTable DS = TA.GetData();
if (DS.Rows.Count > 0)
{
GridView2.DataSource = DS;
GridView2.DataBind();
}
}
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
Control ctrl = e.Row.FindControl("DDL_STATUS_FT");
if (ctrl != null)
{
DropDownList dd = ctrl as DropDownList;
DataSet7TableAdapters.sp_getall_trv_masterTableAdapter TA = new DataSet7TableAdapters.sp_getall_trv_masterTableAdapter();
DataSet7.sp_getall_trv_masterDataTable DS = TA.GetData();
dd.DataTextField = "fld_TName";
dd.DataValueField = "fld_id";
dd.DataSource = DS;
dd.DataBind();
}
}
}
Design Code:
<asp:TemplateField ItemStyle-Width="100px" HeaderText="TYPE">
<ItemTemplate>
<asp:DropDownList ID="DDL_STATUS" runat="server" AutoPostBack="true" Enabled="false" >
</asp:DropDownList>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DDL_edit_STATUS" runat="server" AutoPostBack="true">
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DDL_STATUS_FT" runat="server" AutoPostBack="true">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
I want to show the save data as a selected value. But now the first item show always in dropdownlist. Please help me to do this..

Try this out:
DropDownList dd = ctrl as DropDownList;
DataSet7TableAdapters.sp_getall_trv_masterTableAdapter TA = new DataSet7TableAdapters.sp_getall_trv_masterTableAdapter();
DataSet7.sp_getall_trv_masterDataTable DS = TA.GetData();
dd.DataTextField = "fld_TName";
dd.DataValueField = "fld_id";
dd.DataSource = DS;
dd.DataBind();
dd.SelectedValue= "";//Put your value here which needs to be selected

You can set the 'SelectedValue' on your dropdownlist on clientside like
SelectedValue='<%# Eval("fieldname") %>'

As you are not setting back the index/value what you saved in the database so after every binding it will by default shows up the first item

Related

Input string was not in a correct format in grid view RowDataBound?

This is HTML dropdown list.
On edit button doesn't bind exact value of label from Item template field
<asp:TemplateField HeaderText="Country">
<EditItemTemplate>
<asp:DropDownList ID="ddlcountry" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlcountry_SelectedIndexChanged"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblcountry" runat="server" Text='<%#Eval("cnname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="State">
<EditItemTemplate>
<asp:DropDownList ID="ddlstate" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlstate_SelectedIndexChanged"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblstate" runat="server" Text='<%#Eval("sname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<EditItemTemplate>
<asp:DropDownList ID="ddlcity" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblcity" runat="server" Text='<%#Eval("cname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
And this is the controllers code:
protected void gvcustomgrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
//Find the blood group DropDownList in the Row
DropDownList ddlbloodgroup = (e.Row.FindControl("ddlbg") as DropDownList);
ddlbloodgroup.DataSource = ttdal.getbloodgroup();
ddlbloodgroup.DataTextField = "bg_name";
ddlbloodgroup.DataValueField = "bg_id";
ddlbloodgroup.DataBind();
ddlbloodgroup.SelectedValue = gvcustomgrid.DataKeys[e.Row.RowIndex].Value.ToString();
//Find the country DropDownList in the Row
DropDownList ddlcountry = (e.Row.FindControl("ddlcountry") as DropDownList);
ddlcountry.DataSource = ttdal.getcountry();
ddlcountry.DataTextField = "cnname";
ddlcountry.DataValueField = "cnid";
ddlcountry.DataBind();
ddlcountry.SelectedValue = gvcustomgrid.DataKeys[e.Row.RowIndex].Value.ToString();
//Find the state DropDownList in the Row
DropDownList ddlstate = (e.Row.FindControl("ddlstate") as DropDownList);
ddlstate.DataSource = ttdal.getstate(Convert.ToInt32(ddlcountry.SelectedValue));
ddlstate.DataTextField = "sname";
ddlstate.DataValueField = "sid";
ddlstate.DataBind();
ddlstate.SelectedValue = gvcustomgrid.DataKeys[e.Row.RowIndex].Value.ToString();
//Find the city DropDownList in the Row
DropDownList ddlcity = (e.Row.FindControl("ddlcity") as DropDownList);
ddlcity.DataSource = ttdal.getcity(Convert.ToInt32(ddlstate.SelectedValue));
ddlcity.DataTextField = "cname";
ddlcity.DataValueField = "cid";
ddlcity.DataBind();
ddlcity.SelectedValue = gvcustomgrid.DataKeys[e.Row.RowIndex].Value.ToString();
}
}
}
protected void ddlcountry_SelectedIndexChanged(object sender, EventArgs e)
{
//Find the state DropDownList in the Row
DropDownList ddlcountry = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddlcountry.NamingContainer;
if (row != null)
{
if ((row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlstate = (DropDownList)row.FindControl("ddlstate");
ddlstate.DataSource = ttdal.getstate(Convert.ToInt32(ddlcountry.SelectedValue));
ddlstate.DataValueField = "sid";
ddlstate.DataTextField = "sname";
ddlstate.DataBind();
}
}
}
protected void ddlstate_SelectedIndexChanged(object sender, EventArgs e)
{
//Find the city DropDownList in the Row
DropDownList ddlstate = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddlstate.NamingContainer;
if (row != null)
{
if ((row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlcity = (DropDownList)row.FindControl("ddlcity");
ddlcity.DataSource = ttdal.getcity(Convert.ToInt32(ddlstate.SelectedValue));
ddlcity.DataValueField = "cid";
ddlcity.DataTextField = "cname";
ddlcity.DataBind();
}
}
}
What should I do to get the correct format in grid view RowDataBound?

Gridview, system.data.datarowview' does not contain a property

iam getting a error when trying to make a dropdown list in asp.net. hoping you guys can help because i dont know what else to try anymore.. The error: "system.data.datarowview' does not contain a property with the name 'Suppstatus'.", sounds like ive spelled something wrong but ive tripple checked.
template code:
<asp:TemplateField>
<ItemTemplate>
<asp:Label Text='<%#Eval("Suppstatus") %>' Visible="false" ID="lblsuppStatus" runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="ddlSupStatus"> </asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
Code behind:
protected void grvSupplierStatus_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow && GridView1.EditIndex == e.Row.RowIndex)
{
DropDownList ddlSupStatus = (DropDownList)e.Row.FindControl("ddlSupstatus");
Label lblsuppstatus = (Label)e.Row.FindControl("lblsuppStatus");
DataSet ds = new DataSet();
ds = GetYesNoValue("Suppstatus");
DataTable dt = new DataTable();
dt = ds.Tables[0];
ddlSupStatus.DataSource = dt;
ddlSupStatus.DataTextField = "Suppstatus";
ddlSupStatus.DataValueField = "Suppstatus";
ddlSupStatus.DataBind();
ddlSupStatus.Items.FindByValue(lblsuppstatus.Text).Selected = true;
}
}
catch (Exception ex)
{
}
}
public DataSet GetYesNoValue(string ColumnName)
{
DataTable dtVal = new DataTable();
DataColumn column;
DataRow row;
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = ColumnName;
dtVal.Columns.Add(column);
DataSet dsVal = new DataSet();
dtVal.Rows.Add("--Select--");
dtVal.Rows.Add("Yes");
dtVal.Rows.Add("No");
dsVal.Tables.Add(dtVal);
return dsVal;
}
You're using a circuitous approach to insert your data. You could also
replace
<asp:DropDownList runat="server" ID="ddlSupStatus" ></asp:DropDownList>
with
<asp:DropDownList runat="server" ID="ddlSupStatus" Selected='<%# Bind("Suppstatus") %>'>
<asp:ListItem Text="--Select--" Value="--Select--"></asp:ListItem>
<asp:ListItem Text="Yes" Value="Yes"></asp:ListItem>
<asp:ListItem Text="No" Value="No"></asp:ListItem>
</asp:DropDownList>
without any action codebehind

Add new rows to Asp.net grid view without refresh previous rows values

Hi I have a grid view with two columns text box and drop down list when I add values and click "ADD" button I want to add new row with Previous values,
I do it but my previous values refresh. Please help me.
This is my aspx
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvStudent" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<ItemTemplate>
<asp:DropDownList ID="DropDownListAddress" runat="server" AutoPostBack="true">
<asp:ListItem Text="Select" Value="0"> </asp:ListItem>
<asp:ListItem Text="Address1" Value="1"> </asp:ListItem>
<asp:ListItem Text="Address2" Value="2"> </asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div>
<asp:Button ID="ButtonADD" runat="server" Text="Add" OnClick="ButtonADD_Click" />
</div>
</form>
And this is my output
This is my CodeBehind
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("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Address", typeof(string)));
dr = dt.NewRow();
dr["Name"] = string.Empty;
dr["Address"] = string.Empty;
dt.Rows.Add(dr);
ViewState["StudentTable"] = dt;
gvStudent.DataSource = dt;
gvStudent.DataBind();
}
protected void ButtonADD_Click(object sender, EventArgs e)
{
//Add Rows
}
}
}
There are 3 stpes to do it:
Get data from GridView and save to datatable
Add new row to datatable and save datatable to viewstate
Bind datatable to gridview
private void SaveGridViewDataIntoDataTable()
{
DataTable StudentTable = ViewState["StudentTable"] as DataTable;
foreach (GridViewRow row in gvStudent.Rows)
{
//get ddl value
DropDownList DropDownListAddress = row.FindControl("DropDownListAddress") as DropDownList;
StudentTable.Rows[row.RowIndex]["Address"] = DropDownListAddress.SelectedValue;
//get name from textbox
TextBox TextBoxName = row.FindControl("TextBoxName") as TextBox;
StudentTable.Rows[row.RowIndex]["Name"] = TextBoxName.Text;
}
ViewState["StudentTable"] = StudentTable;
}
private void AddNewRowToGridView()
{
SaveGridViewDataIntoDataTable();
DataTable StudentTable = ViewState["StudentTable"] as DataTable;
StudentTable.Rows.Add("Name", "Select");
gvStudent.DataSource = StudentTable;
gvStudent.DataBind();
}
now subscribe to Gridview RowBound event
<asp:GridView ID="gvStudent" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvStudent_RowDataBound">
also add "RowIndex" Attribute to any of your gridview controls
<asp:TextBox ID="TextBoxName" runat="server" RowIndex='<%# Container.DisplayIndex %>'></asp:TextBox>
Code behind:
protected void gvStudent_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//get name from textbox
TextBox TextBoxName = row.FindControl("TextBoxName") as TextBox;
//get ddl value
DropDownList DropDownListAddress = row.FindControl("DropDownListAddress") as DropDownList;
//get rowindex
int RowIndex = Convert.ToInt32(TextBoxName.Attributes["RowIndex"]);
//get datatable stored in viewstate
DataTable StudentTable = ViewState["StudentTable"] as DataTable;
//assign values to controls
TextBoxName.Text = StudentTable.Rows[RowIndex]["Name"].ToString();
DropDownListAddress.SelectedValue = StudentTable.Rows[RowIndex]["Address"].ToString();
}
}

Get footer row cell values of gridview

I have a gridview with two textboxes in the footer. What's required is get the textbox values, store it to a datatable and then bind the same to the gridview.
I am unable to get the textbox values. They show up empty (as you can see). Where am I going wrong.
ASPX:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False"
ShowFooter="true" OnRowDataBound="gv_RowDataBound"
OnRowCommand="gv_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit">
</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" Text="Update"
CommandName="Update"></asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" Text="Cancel"
CommandName="Cancel"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="S.No">
<ItemTemplate>
<%#Container.DataItemIndex %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lbId" runat="server" Text='<%#Eval("id") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtId" runat="server" Text='<%#Eval("id") %>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewId" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtNewId"
SetFocusOnError="true"
ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NAME">
<ItemTemplate>
<asp:Label ID="lbName" runat="server" Text='<%#Eval("name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%#Eval("name") %>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtNewName" SetFocusOnError="true"
ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDelete" runat="server" Text="Delete"
CommandName="Delete"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkInsert" runat="server" Text="Insert"
CommandName="Insert" ></asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CS:
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
DataTable dt = new DataTable();
switch (e.CommandName)
{
case "Insert":
GridViewRow fRow = gv.FooterRow;
dt.Columns.Add("id");
dt.Columns.Add("name");
dt = (DataTable)ViewState["students"];
DataRow dr = dt.NewRow();
dr["id"] = ((TextBox)fRow.FindControl("txtNewId")).Text;
dr["name"] = ((TextBox)fRow.FindControl("txtNewName")).Text;
dt.Rows.Add(dr);
ViewState["students"] = dt;
gv.DataSource = ViewState["students"];
gv.DataBind();
break;
}
}
The textboxes are txtNewId, txtNewName.
Do not use grid_Row command for insert. Use button click event
like this. It will solve your problem
protected void OnCmdInsertClick(object sender, EventArgs e)
{
//Grid's footer row
var footerRow = gv.FooterRow;
if(footerRow !=null)
{
//get your textbox instances
var txtNewId = (TextBox) footerRow.FindControl("txtNewId");
var txtNewName = (TextBox) footerRow.FindControl("txtNewName");
// Check for null
if(txtNewId !=null && txtNewName !=null)
{
var dt = (DataTable)ViewState["students"];
DataRow dr = dt.NewRow();
dr["id"] = txtNewId.Text;
dr["name"] = txtNewName.Text;
dt.Rows.Add(dr);
ViewState["students"] = dt;
gv.DataSource = ViewState["students"];
gv.DataBind();
}
}
}
In the button click event, use the following to get the actual GridViewRow of the footerL
protected void insertButton_Click(object sender, EventArgs e)
{
// This is the crux -
GridViewRow row = (GridViewRow)((sender as Button).NamingContainer);
// ...
// then you can get your textboxes
// Since we know it's an insert
dt.Columns.Add("id");
dt.Columns.Add("name");
dt = (DataTable)Session["students"];
DataRow dr = dt.NewRow();
TextBox txtnewid = (TextBox) row.FindControl("txtNewId");
TextBox txtnewName = (TextBox) row.FindControl("txtNewName");
dr["id"] = txtnewid.Text;
dr["name"] = txtnewName.Text ;
dt.Rows.Add(dr);
Session["students"] = dt;
gv.DataSource = dt;
gv.DataBind();
}
EDIT
The reason viewstate didn't work is because the viewstate lasts only between postbacks. Sessions stay alive for the duration of the user's session. The default is 20 minutes of idle time.
You would normally use ViewState for persisting data between pages during a postback.
This doesn't address best practice, it's just what it is.
Please check whether you are binding the grid view correctly in the Page Load. What i mean to say is whether you are binding with in the if condidtion
if(!IspostBack)
{
BindGridView();
}
I hope this helps. Check it out..
To bind the footer with data, use the below code
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
TextBox txtNewId = (TextBox)e.Row.FindControl("txtNewId");
txtNewId.Text = "New 01";
}
}
...and to retrieve value from the footer textbox,
TextBox txtNewId = (TextBox)gvGrid.FooterRow.FindControl("txtNewId");
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
DataTable dt = new DataTable();
if (e.CommandName.Equals("Insert"))
{
GridViewRow fRow = gv.FooterRow;
dt.Columns.Add("id");
dt.Columns.Add("name");
dt = (DataTable)ViewState["students"];
DataRow dr = dt.NewRow();
TextBox txtnewid = (TextBox) fRow.FindControl("txtNewId");
TextBox txtnewName = (TextBox) fRow.FindControl("txtNewName");
dr["id"] = txtnewid.Text;
dr["name"] = txtnewName.Text ;
dt.Rows.Add(dr);
ViewState["students"] = dt;
gv.DataSource = ViewState["students"];
gv.DataBind();
}
}
Use This,
TextBox txtName = GridView1.FooterRow.FindControl("yourtextboxId") as TextBox;
string name = txtName.Text;
Or
GridViewRow row = ((GridView)sender).FooterRow;
TextBox txtName = (TextBox)row.FindControl("yourtextboxId");
if (txtName == null)
{
return;
}
string name = txtName.Text;
I had the same problem and the best way to get the value is using:
((TextBox)<grid_name>.FooterRow.FindControl("<textBox_id>")).Text
I hope this helps.

textboxes gets cleared while saving

I have a gridview in the popup, with 3 columns, out of which 2 are textbox column. I have added the textbox dynamically in the row data bound event. when data is entered and save button is clicked,the textboxes gets cleared and the empty values are saved. can any one one help me on this. thanks in advance
code here:
for (int r = 0; r < GridView2.Rows.Count; r++)
{
string sub_details = "";
string remarks = "";
GridViewRow gRow1 = GridView2.Rows[r];
// TextBox tb = (TextBox)gRow.Cells[2].FindControl("txt");
TextBox tb1 = (TextBox)gRow1.Cells[1].FindControl("txt1");
TextBox tb2 = (TextBox)gRow1.Cells[2].FindControl("txt2");
if (tb1 != null)
{
sub_details = tb1.Text;
TextBox1.Text = sub_details;
}
if (tb2 != null)
{
remarks= tb2.Text;
}
OdbcConnection DbConnection1 = new OdbcConnection(con1);
OdbcCommand DbCommand1 = DbConnection1.CreateCommand();
try
{
DbConnection1.Open();
DbCommand1.CommandText = "insert into tbl_campboss_report(site,tdate,entered_by,entered_time,details,camp_boss,sub_details,remarks)values('" + drpSites.SelectedItem.Text + "','" + txtDate.Text + "','" + Session["uname"].ToString() + "'," + ss + ",'" + lstDetails.SelectedItem.Text + "','" + txtCampBoss.Text + "','" + sub_details + "','" + remarks + "')";
int t1 = DbCommand1.ExecuteNonQuery();
if (t1 == 1)
{
DbConnection1.Close();
}
}
catch (Exception ee)
{
DbConnection1.Close();
}
}
You can achieve this task easily by placing your textboxes inside
template fields in your footer row with a save button. There you
can save these values to the database row by row.
Using CellIndex could fail if you add a column later to your gridview.
Your database code is prone to SQL injection, I advise you to use paramterized queries
Check below example
ASPX
<asp:GridView ID="gvCustomer" runat="server" AutoGenerateColumns="False"
ShowFooter="True" EmptyDataText="<h2>No records found </h2>"
onrowdeleting="gvCustomer_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="First name">
<FooterTemplate>
First Name:<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblFirstName" Text='<%#Bind("FirstName") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last name" >
<FooterTemplate>
Last Name:
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblLastName" Text='<%#Bind("LastName") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Favorite fruit">
<FooterTemplate>
Favorite fruit:
<asp:DropDownList ID="ddlFavFruit" runat="server">
<asp:ListItem Text="Apple" Value="1"></asp:ListItem>
<asp:ListItem Text="Mango" Value="2"></asp:ListItem>
<asp:ListItem Text="Orange" Value="3">Tomato</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnSave" runat="server" Text="Save"
onclick="btnSave_Click" />
</FooterTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlFruits" runat="server" Enabled="False" selectedValue='<%#Bind("FruitID") %>'>
<asp:ListItem Text="Apple" Value="1"></asp:ListItem>
<asp:ListItem Text="Mango" Value="2"></asp:ListItem>
<asp:ListItem Text="Orange" Value="3">Tomato</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Codebehind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (ViewState["myData"] == null)
{
// initialize datatable
dt = new DataTable();
dt.Columns.Add(new DataColumn("Id", typeof(int)));
dt.Columns.Add(new DataColumn("FirstName", typeof(string)));
dt.Columns.Add(new DataColumn("LastName", typeof(string)));
dt.Columns.Add(new DataColumn("FruitID", typeof(int)));
dt.Columns[0].AutoIncrement = true;
dt.Columns[0].AutoIncrementSeed = 1;
// Add sample data
for (int i = 0; i <= 5; i++)
{
DataRow dr = dt.NewRow();
dr["FirstName"] = "Scott";
dr["LastName"] = "Tiger";
dr["FruitID"] = "2";
dt.Rows.Add(dr);
}
ViewState["myData"] = dt;
}
else
{
dt = ViewState["myData"] as DataTable;
}
gvCustomer.DataSource = dt;
gvCustomer.DataBind();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
// fetch controls from footer
GridViewRow footerRow = ((Button)sender).NamingContainer as GridViewRow;
if (footerRow != null)
{
// Fetch footer controls
TextBox txtFirstName = footerRow.FindControl("txtFirstName") as TextBox;
TextBox txtLastName = footerRow.FindControl("txtLastName") as TextBox;
DropDownList ddlFruits = footerRow.FindControl("ddlFavFruit") as DropDownList;
// Save to datatable
dt = ViewState["myData"] as DataTable;
DataRow dr = dt.NewRow();
dr["FirstName"] = txtFirstName.Text.ToString();
dr["LastName"] = txtLastName.Text.ToString();
dr["FruitID"] = ddlFruits.SelectedValue;
dt.Rows.Add(dr);
gvCustomer.DataSource = dt;
gvCustomer.DataBind();
ViewState["myData"] = dt;
}
}
//This Metghod Will not Clear The Controls
//Keep this Method in Your .Aspx.cs Page
protected override void CreateChildControls()
{
base.CreateChildControls();
// Keep your GridView Binding Code
}

Categories