how to delete textboxes dynamically - c#

cs code
protected void DeleteNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["dtCurrentTable"] != null)
{
DataTable DeldtCurrentTable = (DataTable)ViewState["dtCurrentTable"];
DataRow drCurrentRow = null;
if (DeldtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i > DeldtCurrentTable.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");
DropDownList box2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("ddldatatype");
drCurrentRow = DeldtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i - 1;
drCurrentRow["Column1"] = box1.Text;
drCurrentRow["Column2"] = box2.Text;
//drCurrentRow["Column3"] = box3.Text;
rowIndex--;
}
//add new row to DataTable
DeldtCurrentTable.Rows.Remove(drCurrentRow);
//Store the current data to ViewState
ViewState["dtCurrentTable"] = DeldtCurrentTable;
//Rebind the Grid with the current data
Gridview1.DataSource = DeldtCurrentTable;
Gridview1.DataBind();
}
}
}
protected void ButtonDel_Click(object sender, EventArgs e)
{
DeleteNewRowToGrid();
}
aspx code
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Column Name">
<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="Data Type">
<ItemTemplate>
<asp:DropDownList ID="ddldatatype" runat="server">
<asp:ListItem>varchar</asp:ListItem>
<asp:ListItem>int</asp:ListItem>
<asp:ListItem>numeric</asp:ListItem>
<asp:ListItem>uniqueidentifier</asp:ListItem>
<asp:ListItem>char</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click"/>
<asp:Button ID="ButtonDel" runat="server" Text="Delete Row" OnClick="ButtonDel_Click"/>
<input type="hidden" runat="server" value="0" id="hiddencount" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
I have done with add rwo, now I want to delete

you are trying to deleta a row "drCurrentRow" that's not even in your DataTable, because you created this drCurrentRow = DeldtCurrentTable.NewRow(); yourself and didn't even insert it (no use anyway).
You have to search the rows to delete from your source like this:
var toDel = DeldtCurrentTable.Where(row => /* true if found */).ToArray();
foreach(var t in toDel) DeldtCurrentTable.Rows.Remove(t);
and then you can reiterate and set your rownumbers again.
Finaly set the the ViewState and the DataSource + DataBind it
BTW: your naming is really frustrating - what the heck does "DeleteNewRowToGrid" mean? Do you want to delete some new row? What is the a new row in this case?
So: Which row should be deleted here?

Related

How to remove a row from gridview on Row Command?

I have a grid view where data is dyanmically added. I need an onRowCommand where the selected row will be deleted. I need the row to be deleted only from the grid view.
protected void LoadDataTable()
{
string header = lblHeader.Text;
string aa = tv.SelectedNode.Parent.Value;
string child = tv.SelectedNode.Text;
string parent = tv.SelectedNode.Parent.Text;
var dt = new DataTable();
dt.Columns.Clear();
dt.Rows.Clear();
dt.Columns.Add("TargetGLId");
dt.Columns.Add("TargetHead");
dt.Columns.Add("Parent");
dt.Columns.Add("Header");
foreach (GridViewRow row in gvBudgetSetup.Rows)
{
var lblheader = (Label)row.FindControl("lblHeader");
var lblparticular = (Label)row.FindControl("lblParticular");
var lblGlId = (Label)row.FindControl("lblGLId");
var lblparent = (Label)row.FindControl("lblParent");
var dr = dt.NewRow();
dr["TargetHead"] = lblparticular.Text;
dr["TargetGLID"] = lblGlId.Text;
dr["Parent"] = lblparent.Text;
dr["Header"] = lblHeader.Text;
dt.Rows.Add(dr);
}
var dr1 = dt.NewRow();
dr1["TargetHead"] = child;
dr1["TargetGLID"] = tv.SelectedValue;
dr1["Parent"] = parent;
dr1["Header"] = header;
dt.Rows.Add(dr1);
gvBudgetSetup.DataSource = null;
gvBudgetSetup.DataBind();
gvBudgetSetup.DataSource = dt;
gvBudgetSetup.DataBind();
}
I have tried this code to delete the row but it is not working.
protected void gvBudgetSetup_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete1")
{
// gvBudgetSetup.DeleteRow(e.Row.RowIndex);
GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
int getRowIndex = gvr.RowIndex;
gvBudgetSetup.DeleteRow(getRowIndex);
}
}
This is the Gridview created. The gridview is not connected to any database. The data in the gridview is added from the back-end codes.
<asp:GridView ID="gvBudgetSetup" runat="server" CssClass="table1" AutoGenerateColumns="false" ShowFooter="true" OnSelectedIndexChanged="gvBudgetSetup_SelectedIndexChanged"
ShowHeaderWhenEmpty="true" OnRowDataBound="gvBudgetSetup_RowDataBound" OnRowCommand="gvBudgetSetup_RowCommand" OnRowDeleting="gvBudgetSetup_RowDeleting" Width="100%">
<FooterStyle CssClass="GridFooter" />
<RowStyle CssClass="GridItem" />
<columns>
<asp:TemplateField HeaderText="Sn">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="GL Id">
<ItemTemplate>
<asp:Label ID="lblGLId" runat="server" Text='<%# Bind("TargetGLID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header">
<ItemTemplate>
<asp:Label ID="lblHeader" runat="server" Text='<%# Bind("Header") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Parent">
<ItemTemplate>
<asp:Label ID="lblParent" runat="server" Text='<%# Bind("Parent") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Child">
<ItemTemplate>
<asp:Label ID="lblParticular" runat="server" Text='<%# Bind("TargetHead") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton runat="server" Text="Delete" CommandName="Delete1"
ID="lnkDelete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</columns>
<EmptyDataTemplate>
"There are no data to display..."
</EmptyDataTemplate>
</asp:GridView>
Better way to do is have a flag in the data source that one row is flagged(deleted) and bind it again. To delete a datarow from a GridViewEvent, you have to re bind the datasource again.
Introduce a Flag column in your data source
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
//Update the flag in datasource using the CommandArgument value
//Bind the datasource again.
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int getRowIndex = gvr.RowIndex;
gvBudgetSetup.DeleteRow(getRowIndex);
Use this updated code

How to Find label control value in Gridview Footer ButtonClick Event

Gridview Aspx Page
<asp:GridView ID="GridView2" runat="server" ShowFooter="true" GridLines="None" AutoGenerateColumns="False" CssClass="table table-hover">
<Columns>
<asp:TemplateField HeaderText="S.no">
<ItemTemplate><%#Container.DataItemIndex+1 %>
<asp:Label ID="lblReqNo1" Visible="false" runat="server" Text='<%#Eval("ReqNo")%>' ></asp:Label>
<asp:Label ID="lblFranchise_id" Visible="false" runat="server" Text='<%#Eval("franchise_id")%>' ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAccept" runat="server" CssClass="btn btn-danger"
Text="Accept Request" onclick="btnAccept_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Product Name" DataField="p_name" />
<asp:BoundField HeaderText="Quantity" DataField="Qty" />
<asp:BoundField HeaderText="Dealer Price" DataField="DP" />
<asp:BoundField HeaderText="Amount" DataField="amt" />
</Columns>
</asp:GridView>
C# Code
Button Click event which is in Gridview Footer Template
protected void btnAccept_Click(object sender, EventArgs e)
{
// GridViewRow row = (GridViewRow)((sender as Button).NamingContainer);
using (GridViewRow row = (GridViewRow)((Button)sender).NamingContainer)
{
Label lblReqNo = (Label)row.FindControl("lblReqNo1");
Label lblFranchise_id = (Label)row.FindControl("lblFranchise_id");
objFund.Transfer_id = int.Parse(lblReqNo.Text);
objFund.Type = 9;
int a = objFund.Insert();
objFund.Transfer_id = int.Parse(lblFranchise_id.Text);//franchise Id
objFund.CreditAmt = float.Parse(lblReqNo.Text);
objFund.Type = 5;
int b = objFund.Insert();
if (b > 0)
{
msg.Alert("Request accepted and mount Debited ");
}
}
}
it throws exception which is below
Object reference not set to an instance of an object.
Label lblReqNo = (Label)row.FindControl("lblReqNo1");//
by this line I'm getting only Null Values.How do i find Label Value?
Thanks
You can check row type wether it is header row or data row...
.. i.e. if it is data row then only your code will will execute
if (row.RowType == DataControlRowType.DataRow)
{
Label lblReqNo = (Label)row.FindControl("lblReqNo1");
Label lblFranchise_id = (Label)row.FindControl("lblFranchise_id");
objFund.Transfer_id = int.Parse(lblReqNo.Text);
objFund.Type = 9;
int a = objFund.Insert();
objFund.Transfer_id = int.Parse(lblFranchise_id.Text);//franchise Id
objFund.CreditAmt = float.Parse(lblReqNo.Text);
objFund.Type = 5;
int b = objFund.Insert();
if (b > 0)
{
msg.Alert("Request accepted and mount Debited ");
}
}

Row command with Link button in GridView

I have two GridViews. GridView1 contains 2 link buttons in a column. When I select a link button in GridView1, the details of the link button should be displayed in GridView2.
GridView2 contains a column with radio buttons. I need to fill the radio buttons dynamically from the database.
How can I fill the Radio button list of GridView2 by using GridView1_RowCommand? Or Can I get it from the RowDataBound event of GridView2?
code behind:
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Yes")
{
GridViewRow gvRow = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
int RowIndex = gvRow.RowIndex;
Int32 iAppID = Convert.ToInt32(GridView1.DataKeys[gvRow.RowIndex].Value.ToString());
dset = userApps.UserSelectedApp(iUserID, iAppID);
if (dset.Tables[0].Rows.Count > 0)
{
GridViewRow gRow = GridView2.Rows[RowIndex];//I need to create object to this Gridview2, and fill the radiobutton list with some values
RadioButtonList rdbtnSubPlans = (RadioButtonList)e.gRow.Cells[2].FindControl("rdbSubPlans");
ds = userApps.UpgradePlans(iUserID, iAppID);
if (ds != null)
{
rdbtnSubPlans.DataSource = ds;
rdbtnSubPlans.DataValueField = "PlanID";
rdbtnSubPlans.DataTextField = "Plans";
rdbtnSubPlans.DataBind();
}
}
}
if (e.CommandName == "No")
{}
dtset = user.UserSelectedAppication(iUserID, iAppID);
GridView2.DataSource = dtset;
GridView2.DataBind();
MultiView1.SetActiveView(viewRenewOrUpdate);
}
}
ASPX code for the GridViews
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ApplicationID"
OnRowDataBound="GridView1_RowDataBound" OnRowCommand="GridView1_RowCommand"
OnSorting="GridView1_Sorting" OnDataBound="GridView1_DataBound"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField HeaderText="S.No" ItemStyle-HorizontalAlign="center" HeaderStyle-HorizontalAlign="center">
<ItemTemplate>
<asp:Label ID="l1" runat="server" Text="1"></asp:Label>
</ItemTemplate>
<HeaderStyle Width="10%" />
</asp:TemplateField>
< Some Bound Fields>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="lnkYes" runat="server" Text="Yes"
CssClass="lnkbtn" Visible="false" commandname="Yes" Width="100px" >
</asp:LinkButton>
<asp:LinkButton ID="lnkNo" runat="server" CssClass="lnkbtn" Text="No"
Visible="false" commandname="No" ToolTip="No and Yes current plan" Width="100px" >
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:GridView ID="GridView2" runat="server" DataKeyNames="ApplicationID"
OnRowDataBound="GridView2_RowDataBound">
<Columns>
<asp:BoundField DataField="ApplicationName" HeaderText="Application name">
<HeaderStyle Width="30%" />
<ItemStyle CssClass="col" />
</asp:BoundField>
<asp:TemplateField HeaderText="Plans">
<ItemTemplate>
<asp:RadioButtonList ID="rdbSubPlans" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="rdbSubPlan_OnSelectedIndexChanged" Enabled="false">
</asp:RadioButtonList>
</ItemTemplate>
<ItemStyle CssClass="col" />
</Columns>
</asp:GridView>
Fill Gridview2 first, and then do the following corrections:
GridViewRow gRow = GridView2.Rows[0]
RadioButtonList rdbtnPlans = (RadioButtonList)gRow.FindControl("rdbPlans");

Add Row to ASP.NET GridView?

I have the following GridView which has a couple DropDownLists and TextBoxes. How can I add a new row to it, while persisting the existing GridView. I would like to Add the New row with the LinkButton. I am not using DataSource Controls and the GridView is currently populated via a DataTable. Here is the GridView:
<asp:LinkButton ID="btnAdd" runat="server" Text="Add Room"
onclick="btnAdd_Click"></asp:LinkButton>
<asp:GridView ID="gvRP" runat="server" AutoGenerateColumns="false"
onrowdatabound="gvRP_RowDataBound"
onrowediting="gvRP_RowEditing">
<Columns>
<asp:TemplateField HeaderText="Room" ItemStyle-Width="100%">
<ItemTemplate>
<asp:Label runat="server" Text="Room"></asp:Label>
<asp:DropDownList ID="ddlRoom" runat="server" AutoPostBack="True" DataTextField="Name"
DataValueField="Id" AppendDataBoundItems="true" OnSelectedIndexChanged="ddlRoom_SelectedIndexChanged">
<asp:ListItem Value="-1">Select...</asp:ListItem>
</asp:DropDownList>
<asp:Label runat="server" AssociatedControlID="ddlRate" Text="Rate" ID="lblRate"></asp:Label><asp:DropDownList
ID="ddlRate" runat="server" AppendDataBoundItems="true" DataTextField="Name"
DataValueField="Id">
<asp:ListItem Value="-1">Select...</asp:ListItem>
</asp:DropDownList>
<asp:Label runat="server" Text="Adults"></asp:Label>
<asp:TextBox ID="txtAdults" Text='<%#Bind("Adults") %>' runat="server" Width="25px"></asp:TextBox>
<asp:Label runat="server" Text="Children"></asp:Label>
<asp:TextBox ID="txtChildren" Text='<%#Bind("Children") %>' runat="server" Width="25px"></asp:TextBox>
<asp:Label runat="server" Text="Check In"></asp:Label>
<asp:TextBox ID="txtCheckIn" Text='<%#Bind("CheckIn") %>' runat="server" Width="75px"></asp:TextBox>
<asp:Label runat="server" Text="Check Out"></asp:Label>
<asp:TextBox ID="txtCheckOut" Text='<%#Bind("CheckOut") %>' runat="server" Width="75px"></asp:TextBox>
<h3>Rates</h3>
<asp:GridView ID="gvR" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Rate" />
<asp:BoundField DataField="Effective" HeaderText="Effective" />
<asp:BoundField DataField="Expire" HeaderText="Expire" />
<asp:BoundField DataField="Amount" HeaderText="Amount" />
<asp:BoundField DataField="Code" HeaderText="Currency" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Usually I try and do an example, but this one is quite thorough, and I don't "think" the url is going anywhere. Please refer to this link for a comprehensive example.
Here's the important code.
grid
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" />
</FooterTemplate>
code behind
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid()
}
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
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
Put Label control or Textbox as you like inside ItemTemplate if you put it at last it'll be displayed at last, for example
<ItemTemplate>
....
<asp:Label Text="foo" runat="server" />
</ItemTemplate>
or
<ItemTemplate>
<asp:Label Text="foo" runat="server" />
....
</ItemTemplate>
I decided to go with this solution:
DataTable dt = new DataTable();
DataColumn dcRoom = new DataColumn("Room", typeof(DropDownList));
DataColumn dcAdults = new DataColumn("Adults", typeof(string));
DataColumn dcChildren = new DataColumn("Children", typeof(string));
DataColumn dcCheckIn = new DataColumn("CheckIn", typeof(string));
DataColumn dcCheckOut = new DataColumn("CheckOut", typeof(string));
dt.Columns.AddRange(new DataColumn[] { dcRoom, dcAdults, dcChildren, dcCheckIn, dcCheckOut });
dt.Rows.Add(new object[] { new DropDownList(), "", "", "", "" });
gvRP.DataSource = dt;
gvRP.DataBind();
How does it know What to put in the DropDown (Select...) and I haven't specified two DropDowns, yet it still puts the second DropDown.
namespace gridview_row_add
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataGridViewTextBoxColumn columntype = new DataGridViewTextBoxColumn();
columntype.HeaderText = "Type";
columntype.Width = 80;
dataGridView1.Columns.Add(columntype);
DataGridViewTextBoxColumn columnparameters = new DataGridViewTextBoxColumn();
columnparameters.HeaderText = "Parameters";
columnparameters.Width = 320;
dataGridView1.Columns.Add(columnparameters);
DataGridViewTextBoxColumn columndisplay = new DataGridViewTextBoxColumn();
columndisplay.HeaderText = "Display";
columndisplay.Width = 150;
dataGridView1.Columns.Add(columndisplay);
DataGridViewTextBoxColumn enumuration = new DataGridViewTextBoxColumn();
enumuration.HeaderText = "Format";
enumuration.Width = 90;
dataGridView1.Columns.Add(enumuration);
dataGridView1.AllowUserToAddRows = false;//please add this if u don't want to add exta rows or else make it true.
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.Rows.Add();//here on each click the new row will be added.
int rowcount = dataGridView1.Rows.Count;
dataGridView1.Rows[rowcount - 1].Cells[0].Value = "data" + rowcount.ToString();
dataGridView1.Rows[rowcount-1].Cells[1].Value = "field";
dataGridView1.Rows[rowcount-1].Cells[2].Value = "xyzzz";
dataGridView1.Rows[rowcount-1].Cells[3].Value = "hts";
rowcount++;
}
}
}
this code works fine for me. in this code i added four headers in girdview, you can change them as per your requirement..one button click it will add new row first then data got filled in that row..
hope this will work for you..

How to find a control in a row and bind it to data

I have a gridview and in the gridview i got a item template as follows
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlProductNames">
</asp:DropDownList>
</ItemTemplate>
Now on every row in the gridview i need to bind this to the data, but i am having trouble finding it and binding it to the data.
The gridview has 4 templatefields with 1 itemtemplate within each template field like this
<asp:TemplateField HeaderText="Product Name" ItemStyle-HorizontalAlign = "Center" >
<ItemTemplate>
<asp:TextBox runat="server" ID="txt1" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Products" ItemStyle-HorizontalAlign = "Center" >
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlProductNames">
</asp:DropDownList>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Image" ItemStyle-HorizontalAlign = "Center" >
<ItemTemplate>
<asp:FileUpload runat="server" ID="image" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Active" ItemStyle-HorizontalAlign = "Center">
<ItemTemplate>
<asp:CheckBox Text="Active" runat="server" ID="active" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
And I am trying to bind the drop down as follows
protected void Grid_OnRowDataBound(Object sender, GridViewRowEventArgs e)
{
// Bind Products
Product productManager = new Product();
TList<Product> dsProduct= productManager.GetAll();
DropDownList ddlProducts = Grid.Rows[e.Row.RowIndex].Cells[1].Controls[0].FindControl("ddlProductNames") as DropDownList;
if (dsProduct != null)
{
DataView dvProduct = new DataView(dsProduct.ToDataSet(true).Tables[0]);
dvProduct.Sort = "name asc";
ddlProducts.DataSource = dvBrand;
ddlProducts.DataTextField = "name";
ddlProducts.DataValueField = "productId";
ddlProducts.DataBind();
ListItem li = new ListItem("No Product Selected", "0");
ddlProducts.Items.Insert(0, li);
}
}
I am getting a out of index in the line DropDownList ddlProducts = Grid.Rows[e.Row.RowIndex].Cells[1].Controls[0].FindControl("ddlProductNames") as DropDownList; I am learning this process so i would appreciate some help in terms of what i am doing wrong and what i need to change. I would really appreciate any help.
You must use FindControl to find controls in a TemplateField. You also need to exclude the header-row:
protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow row = ((DataRowView)e.Row.DataItem).Row;
DropDownList ddlProducts = (DropDownList)e.Row.FindControl("ddlProductNames");
ddlProducts.DataSource = someDataSource;
ddlProducts.DataTextField = "name";
ddlProducts.DataValueField = "productId";
ddlProducts.DataBind();
}
}
You also don't need to call productManager.GetAll() for every row in the Grid. You only need to get the products for the current Row. If the source is the same for every row, you should create it before you bind the GridView as member-variable. Then you don't need to retrieve the same data for each row.

Categories