Selected value on a DropDownList inside of a repeater - c#

I'm adding a dropdwonlist inside of my repeater. Now I need to set a selected value for my dropdownlist.. but I'm not being very successful..
private void PhysicianSource()
{
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add("Source");
dt.Columns.Add("ID", Type.GetType("System.String"));
dt.Columns.Add("Desc", Type.GetType("System.String"));
Provider oProvider = new Provider();
List<ProviderLabel> lstprovider = oProvider.RetrievePhysicianList();
foreach (ProviderLabel item in lstprovider)
{
DataRow dr = dt.NewRow();
dr[0] = item.ProviderCode.ID.ToString();
dr[1] = item.Name.ToString();
dt.Rows.Add(dr);
}
drpPhysicianCode.DataSource = ds;
drpPhysicianCode.DataMember = "Source";
drpPhysicianCode.DataTextField = "ID";
drpPhysicianCode.DataValueField = "ID";
drpPhysicianCode.DataBind();
}
asp.net
<asp:Repeater ID="rptrPatientList" runat="server" >
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<tr>
<td class="style2">
<asp:DropDownList ID="DropDownList1"
DataTextField="ID" runat="server"
DataValueField="Desc"
SelectedValue='<%# Eval("Code") %>'
DataSource="ds">
</asp:DropDownList>
</td>
</td>
</tr>
nothing happens on my codes.. help me guys I'm just a beginner on this.. thank you very much..

Hi Ian Ace its better to modify your code a little bit
<asp:Repeater ID="rptProductList" runat="server" OnItemDataBound="rptProductList_ItemDataBound">
<ItemTemplate>
<asp:DropDownList runat="server" ID="MyRepeater" AutoPostBack="true" OnSelectedIndexChanged="DropDownList_SelectedIndexChanged" >
</asp:DropDownList>
</ItemTemplate>
</asp:Repeater>
Now the code behind should be
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillRepeater();
}
}
}
protected void rptProductList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList MyDropDown= (DropDownList)e.Item.FindControl("MyRepeater");
if (MyDropDown!= null)
{
MyDropDown.DataSource = fillDropDown(MyDropDown);
MyDropDown.DataBind();
}
}
}
private DataSet fillDropDown(DropDownList dropDown)
{
// get your collection and return.
}
protected void DropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList MyDropDown= (DropDownList)sender;
string item = MyDropDown.SelectedValue;
}
hope the above example helps.

Try setting the selected value after data binding
Don't set the list contents with every postback. Check for Page.IsPostBack(). Note that this only works if you have ViewState enabled.

//Declare Class Scoped DataSet and DataTable variables
DataSet ds;
DataTable dt;
//Bind repeater and DataSource method
private void PhysicianSource()
{
ds = new DataSet();
dt = ds.Tables.Add("Source");
dt.Columns.Add("ID", Type.GetType("System.String"));
dt.Columns.Add("Desc", Type.GetType("System.String"));
Provider oProvider = new Provider();
List<ProviderLabel> lstprovider = oProvider.RetrievePhysicianList();
foreach (ProviderLabel item in lstprovider)
{
DataRow dr = dt.NewRow();
dr[0] = item.ProviderCode.ID.ToString();
dr[1] = item.Name.ToString();
dt.Rows.Add(dr);
}
drpPhysicianCode.DataSource = ds;
drpPhysicianCode.DataMember = "Source";
drpPhysicianCode.DataTextField = "ID";
drpPhysicianCode.DataValueField = "ID";
drpPhysicianCode.DataBind();
}
//Repeater Item Data Bound event in which we would find Controls to be bound
//and set DataSource and SelectedValue
protected void rptrPatientList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList DropDownList1 = e.Item.FindControl("DropDownList1") as DropDownList;
if (DropDownList1 != null)
{
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
DropDownList1.SelectedValue = // DataBinder Eval 'Code' //;
}
}
}
<asp:Repeater ID="rptrPatientList" runat="server" OnItemDataBound="rptrPatientList_ItemDataBound">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<tr>
<td class="style2">
<asp:DropDownList ID="DropDownList1"
DataTextField="ID" runat="server"
DataValueField="Desc"
SelectedValue='<%# Eval("Code") %>'
DataSource="ds">
</asp:DropDownList>
</td>
</td>
</tr>

The problem occurs because the binding of dropdown occurs after that of repeater control. You can use HTML5 custom attributes, to set your dropdown value into a custom attribute, and then setting it as selected value after the dropdown is databinded. I have binded the dropdown using asp:ObjectDataSource
ASPX
<asp:Repeater ID="rptrPatientList" runat="server" >
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<tr>
<td class="style2">
<asp:DropDownList ID="DropDownList1"
DataTextField="ID" runat="server"
DataValueField="Desc"
SetValue='<%# Eval("Code") %>' datasourceid="dsCategory"
datatextfield="ID" datavaluefield="desc" DataMember = "Source" onprerender="DropDownDataBinding">
</asp:DropDownList>
<asp:ObjectDataSource ID="dsCategory" runat="server" SelectMethod="PhysicianSource" TypeName="WebApplication.WebForm1" />
</td>
</td>
</tr>
CodeBehind
protected void DropDownDataBinding(object sender, EventArgs e) //Method to set the selected value on Category dropdown inside repeater
{
DropDownList sel = (DropDownList)sender;
sel.Value = sel.Attributes["SetValue"];
ListItem li = new ListItem("<< Select >>", "");
sel.Items.Insert(0,li);
}
protected DataSet PhysicianSource()
{
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add("Source");
dt.Columns.Add("ID", Type.GetType("System.String"));
dt.Columns.Add("Desc", Type.GetType("System.String"));
Provider oProvider = new Provider();
List<ProviderLabel> lstprovider = oProvider.RetrievePhysicianList();
foreach (ProviderLabel item in lstprovider)
{
DataRow dr = dt.NewRow();
dr[0] = item.ProviderCode.ID.ToString();
dr[1] = item.Name.ToString();
dt.Rows.Add(dr);
}
return ds;
}

Related

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

How to save drop down list selected value of Item template in database on button click?

Please find image. Here's my whole code, I wanted save each row on save button click. I'm able to get value from cell 0 and cell 1 but unable to get value from cell 2 , where I have drop down list selected value.I'm getting default value "Ignore" instead of selected item. So how do I get selected value of drop down list ?
<div>
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns = "False"
OnRowDataBound = "OnRowDataBound" Width="544px">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:TemplateField HeaderText = "Mapping" >
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" style="font-size: medium; font-family: Cambria" Width="300px">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="Button2" runat="server" Text="Save"
style="font-size: medium; font-family: Cambria" BorderStyle="Groove"
height="32px" Width="116px" onclick="Save_Click" />
</div>
private void BindGrid()
{
DataTable dt = new DataTable();
connection();
cmd = new SqlCommand("Select top 0 * from F3_BC_Product_Mapping_Data", con);
con.Open();
adapter = new SqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds, "mytable");
int j = 1;
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)), new DataColumn("Name", typeof(string)) });
foreach (DataColumn column in ds.Tables[0].Columns)
{
dt.Rows.Add(j,column.ColumnName);
j++;
}
GridView2.DataSource = dt;
GridView2.DataBind();
con.Close();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlMap = (e.Row.FindControl("DropDownList1") as DropDownList);
DataTable dt = new DataTable();
dt = (DataTable)Session["data"];
for (int i = 0; i < dt.Columns.Count; i++)
{
ddlMap.Items.Add(dt.Columns[i].Caption.ToString());
}
ddlMap.Items.Insert(0, new ListItem("Ignore"));
}
}
protected void Save_Click(object sender, EventArgs e)
{
foreach (GridViewRow gr in GridView2.Rows)
{
string cell_1_Value = GridView2.Rows[gr.RowIndex].Cells[0].Text;
string cell_2_Value = GridView2.Rows[gr.RowIndex].Cells[1].Text;
string cell_3_Value = ((DropDownList)gr.FindControl("DropDownList1")).SelectedItem.Value;
}
}
If you are getting default value then you must see binding code. I think you haven't use if(!Page.IsPostBack) before binding and setting default value in drop down. Try to change OnRowDataBound as below.
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && !Page.IsPostBack)
{
DropDownList ddlMap = (e.Row.FindControl("DropDownList1") as DropDownList);
DataTable dt = new DataTable();
dt = (DataTable)Session["data"];
for (int i = 0; i < dt.Columns.Count; i++)
{
ddlMap.Items.Add(dt.Columns[i].Caption.ToString());
}
ddlMap.Items.Insert(0, new ListItem("Ignore"));
}
}

asp.net GridView dynamic line creation with dropmenu as Textbox entry

I have found a dynamic gridview code that creates lines and saves the one you filled last.
In my code i want to parse the droplist selected value text instead of actually writing in the textbox.
I have managed to parse the selectedvalue text in a textbox and for one line everything goes fine, but when i try to create a second line the selected value becomes the same for both lines.
(example: lets say i have a ddl menu with the values "a,b" if i choose the a value first the textbox will be filled ok "a" value, but if i choose b for the second line it will be both "b".
I will be needing 9 textboxes but i have made a simple version of the code containing only 1 textbox for the sake of space.
HTML
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication4.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div style="height: 337px">
<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnSelectedIndexChanged="Gridview1_SelectedIndexChanged">
<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 >
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row"
OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<br />
<br />
<br />
</div>
</form>
</body>
</html>
C# code
namespace WebApplication4
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
setInitialRow();
}
}
protected void Gridview1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
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)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dt.Rows.Add(dr);
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++)
{
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
else
{
Response.Write("Viewstate is null");
}
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[rowIndex].Cells[1].FindControl("TextBox1");
box1.Text = dt.Rows[i]["Column1"].ToString();
rowIndex++;
}
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
So as you'd imagine i tried going
box1.Text = DropDownList1.SelectedValue.ToString();
I tried with view state, but generally i failed.
Thanks for any of the answers guys!
ASPX Page
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
Code Behind
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SetPreviousData();
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
TextBox box1 = (TextBox)Gridview1.Rows[(dt.Rows.Count - 1)].Cells[1].FindControl("TextBox1");
box1.Text = DropDownList1.SelectedValue;
}
}
}
Another Approach you can try is you can directly place dropdownlist in gridview instead of textbox.

Add new row in gridview while button onclick

This is my program that page load the gridview and retrieve the database record to textbox and i put a add new button wish to add new row exactly like that row but the textbox is empty.
I wanted to create a new row in GridView while click add new button while my TextBox is retrieve data from database. I try to run the code but it is nothing happen when i click the button. Hope someone may help. Thanks.
My front end code
<Columns>
<asp:TemplateField HeaderStyle-CssClass="display_none">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Font-Bold="true" Font-Size="Medium">Name</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-CssClass="display_none">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" CssClass="NormalInputTextField" Text='<%#Eval("SLMN") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-CssClass="display_none">
<ItemTemplate>
<asp:Button ID="BtnDelete" runat="server" Text="Delete" CssClass="btn btn-primary" CommandName="remove" CommandArgument='<%# Container.DataItemIndex %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField FooterStyle-BorderStyle="None" HeaderStyle-CssClass="display_none">
<ItemTemplate>
<asp:Button ID="BtnSearch2" runat="server" Text="Search" CssClass="btn btn-primary" CommandName="ViewComments" OnClientClick="javascript:saveData(this,'grid')"/>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" BorderStyle="None"/>
<FooterTemplate>
<asp:Button ID="BtnAdd" runat="server" Text="Add New Row" CssClass="btn btn-primary" OnClick="ButtonAdd_Click"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
My back end code
private void AddNewRowToGrid()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dr = dt.NewRow();
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dt.Rows.Add(dr);
}
My onclick event to call add new function
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
My gridview tag
<grd:MultiSelectGridView ID="grid2" runat="server" Width="500px"
CssClass="paging_gridview" AllowPaging="True"
AutoGenerateColumns ="false" PageSize="10" PagerType="Custom"
ShowFooter="true" OnRowDeleting="grid2_RowDeleting"
MultiSelectDataKeyName="Urid,Name" ShowHeaderWhenEmpty="true"
MultiSelectColumnIndex="0" EnableMultiSelect="false" GridLines="None" BorderStyle="None" OnRowCommand="grid2_RowCommand"
>
i bind my record to gridview by page load
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Loadgrid();
}
}
private void Loadgrid()
{
string branch = txtBranch.Text.Trim();
string name = txtName.Text.Trim();
string sql = "SELECT * FROM fcs_cotmdl WHERE TMDL= '" + name + "'AND CONO='" + branch + "' ";
SqlDataSource2.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr_epsi"].ConnectionString;
SqlDataSource2.ConnectionString = SqlDataSource2.ConnectionString.Replace("Provider=OraOLEDB.Oracle.1;", "");
SqlDataSource con = new SqlDataSource();
SqlDataSource2.SelectCommand = sql;
grid2.DataSourceID = "SqlDataSource2";
grid2.DataBind();
}
Following tutorial details the exact same scenario. Please refer to it.
Adding Dynamic Rows to Gridview on Button Click
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");
//Instead of all the textboxes, use the button as you require.
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
And then the SetPreviousData() Function:
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[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++;
}
}
}
}
Then inside your Click Event:
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
From your Load grid method you should retrieve the data as a data table and bind to grid. And save in in session. Like this:
private void Loadgrid()
{
var dt = new DataTable();
using (var conn = new SqlConnection (ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString()))
{
var command = new SqlCommand();
command.Connection = conn;
command.CommandText = "SELECT * FROM [dbo].[T1]";
command.CommandType = CommandType.Text;
using (var adaptor = new SqlDataAdapter(command))
{
if (conn.State == ConnectionState.Closed) conn.Open();
adaptor.Fill(dt);
if (conn.State == ConnectionState.Open) conn.Close();
}
}
Session["ss"] = dt;
grid2.DataSource = dt;
grid2.DataBind();
}
private void AddNewRowToGrid()
{
DataTable dt = (DataTable) Session["ss"];
DataRow dr = null;
DataRow newBlankRow1 = dt.NewRow();
dt.Rows.Add(newBlankRow1);
grid2.DataSource = dt;
grid2.DataBind();
Session["ss"] = dt;
}
After add an empty row also you need to bind data to grid again.

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();
}
}

Categories