How to delete a row in dynamic Gridview? - c#

I am working, as a test project, for a simple Inventory System in ASP.NET. In one page, I have to make the page for entering Purchase details! I used the dynamic gridview to ease the data entry. I have used this tutorial and this article but I am having problem in deleting the row in the gridview. I have seen this similar post but it was not helpful.
The aspx code is as below -
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Purchase Management</h2>
<asp:GridView ID="PurchaseMgmtGridView" runat="server" ShowFooter="True" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None" OnRowDeleting="PurchaseMgmtGridView_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="Item">
<ItemTemplate>
<asp:DropDownList ID="ItemDropDownList" runat="server" AppendDataBoundItems="true">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ItemUnit">
<ItemTemplate>
<asp:DropDownList ID="ItemUnitDropDownList" runat="server" AppendDataBoundItems="true">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rate">
<ItemTemplate>
<asp:TextBox ID="RateTextBox" runat="server">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Qty.">
<ItemTemplate>
<asp:TextBox ID="QtyTextBox" runat="server">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label ID="TotalLabel" runat="server">
</asp:Label>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAddNewRow" runat="server" Text=" + " OnClick="ButtonAddNewRow_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
</asp:Content>
And here is the aspx.cs Codes -
namespace SmoothInventoryWeb.Pages.ItemManagment
{
public class Item
{
public string Id { get; set; }
public string Name{get; set;}
}
public class ItemUnit
{
public string Id { get; set; }
public string Name{get; set;}
}
public partial class PurchaseManagementPage : System.Web.UI.Page
{
public List<Item> GetItemList()
{
List<Item> itemList = new List<Item>();
itemList.Add(new Item { Id = "1", Name = "Carpet" });
itemList.Add(new Item { Id = "2", Name = "Pasmina Muffler" });
itemList.Add(new Item { Id = "3", Name = "Large Carpet" });
return itemList;
}
public List<ItemUnit> GetItemUnitList()
{
List<ItemUnit> itemUnitList = new List<ItemUnit>();
itemUnitList.Add(new ItemUnit { Id = "1", Name = "Pieces" });
itemUnitList.Add(new ItemUnit { Id = "2", Name = "Dorzen" });
itemUnitList.Add(new ItemUnit { Id = "3", Name = "Gross" });
return itemUnitList;
}
List<Item> itemList = new List<Item>();
List<ItemUnit> itemUnitList = new List<ItemUnit>();
protected void Page_Load(object sender, EventArgs e)
{
this.itemList = GetItemList();
this.itemUnitList = GetItemUnitList();
if (!Page.IsPostBack)
addFirstRowInGridView();
}
private void FillItemDropDownList(DropDownList dropDownList)
{
if (dropDownList == null)
return;
foreach (Item item in itemList)
{
dropDownList.Items.Add(new ListItem(item.Name.ToString(), item.Id.ToString()));
}
}
private void FillItemUnitDropDownList(DropDownList dropDownList)
{
if (dropDownList == null)
return;
foreach (ItemUnit itemUnit in itemUnitList)
{
dropDownList.Items.Add(new ListItem(itemUnit.Name.ToString(), itemUnit.Id.ToString()));
}
}
protected void ButtonAddNewRow_Click(object sender, EventArgs e)
{
AddNewRow();
}
private void addFirstRowInGridView()
{
DataTable dataTable = new DataTable();
dataTable.Columns.Add(new DataColumn("Item", typeof(string)));
dataTable.Columns.Add(new DataColumn("ItemUnit", typeof(string)));
dataTable.Columns.Add(new DataColumn("Rate", typeof(string)));
dataTable.Columns.Add(new DataColumn("Qty", typeof(string)));
dataTable.Columns.Add(new DataColumn("Total", typeof(string)));
DataRow dataRow = dataTable.NewRow();
dataRow["Item"] = string.Empty;
dataRow["ItemUnit"] = string.Empty;
dataRow["Rate"] = string.Empty;
dataRow["Qty"] = string.Empty;
dataRow["Total"] = string.Empty;
dataTable.Rows.Add(dataRow);
ViewState["CurrentTable"] = dataTable;
PurchaseMgmtGridView.DataSource = dataTable;
PurchaseMgmtGridView.DataBind();
DropDownList itemDropDownList =
(DropDownList)PurchaseMgmtGridView.Rows[0].Cells[0].FindControl("ItemDropDownList");
DropDownList itemUnitDropDownList =
(DropDownList)PurchaseMgmtGridView.Rows[0].Cells[1].FindControl("ItemUnitDropDownList");
FillItemDropDownList(itemDropDownList);
FillItemUnitDropDownList(itemUnitDropDownList);
}
private void AddNewRow()
{
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++)
{
DropDownList itemDropDownList =
(DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[0].FindControl("ItemDropDownList");
DropDownList itemUnitDropDownList =
(DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[1].FindControl("ItemUnitDropDownList");
TextBox rateTextBox =
(TextBox)PurchaseMgmtGridView.Rows[rowIndex].Cells[2].FindControl("RateTextBox");
TextBox qtyTextBox =
(TextBox)PurchaseMgmtGridView.Rows[rowIndex].Cells[3].FindControl("QtyTextBox");
Label totalLabel =
(Label)PurchaseMgmtGridView.Rows[rowIndex].Cells[4].FindControl("TotalLabel");
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows[i - 1]["Item"] = itemDropDownList.SelectedItem.ToString();
dtCurrentTable.Rows[i - 1]["ItemUnit"] = itemUnitDropDownList.SelectedItem.ToString();
dtCurrentTable.Rows[i - 1]["Rate"] = rateTextBox.Text;
dtCurrentTable.Rows[i - 1]["Qty"] = qtyTextBox.Text;
dtCurrentTable.Rows[i - 1]["Total"] = totalLabel.Text;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
PurchaseMgmtGridView.DataSource = dtCurrentTable;
PurchaseMgmtGridView.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++)
{
DropDownList itemDropDownList =
(DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[0].FindControl("ItemDropDownList");
DropDownList itemUnitDropDownList =
(DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[1].FindControl("ItemUnitDropDownList");
TextBox rateTextBox =
(TextBox)PurchaseMgmtGridView.Rows[rowIndex].Cells[2].FindControl("RateTextBox");
TextBox qtyTextBox =
(TextBox)PurchaseMgmtGridView.Rows[rowIndex].Cells[3].FindControl("QtyTextBox");
Label totalLabel =
(Label)PurchaseMgmtGridView.Rows[rowIndex].Cells[4].FindControl("TotalLabel");
FillItemDropDownList(itemDropDownList);
FillItemUnitDropDownList(itemUnitDropDownList);
if (i < dt.Rows.Count - 1)
{
//itemDropDownList.SelectedValue = dt.Rows[i]["Item"].ToString();
//itemUnitDropDownList.SelectedValue = dt.Rows[i]["ItemUnit"].ToString();
itemDropDownList.ClearSelection();
itemDropDownList.Items.FindByText(dt.Rows[i]["Item"].ToString()).Selected = true;
itemUnitDropDownList.ClearSelection();
itemUnitDropDownList.Items.FindByText(dt.Rows[i]["ItemUnit"].ToString()).Selected = true;
}
rateTextBox.Text = dt.Rows[i]["Rate"].ToString();
qtyTextBox.Text = dt.Rows[i]["Qty"].ToString();
totalLabel.Text = dt.Rows[i]["Total"].ToString();
rowIndex++;
}
}
}
}
protected void PurchaseMgmtGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
SetRowData();
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
int rowIndex = Convert.ToInt32(e.RowIndex);
if (dt.Rows.Count > 1)
{
dt.Rows.Remove(dt.Rows[rowIndex]);
drCurrentRow = dt.NewRow();
ViewState["CurrentTable"] = dt;
PurchaseMgmtGridView.DataSource = dt;
PurchaseMgmtGridView.DataBind();
for (int i = 0; i < PurchaseMgmtGridView.Rows.Count - 1; i++)
{
PurchaseMgmtGridView.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
}
SetPreviousData();
}
}
}
private void SetRowData()
{
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++)
{
DropDownList itemUnitDropDownList =
(DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[1].FindControl("ItemUnitDropDownList");
DropDownList itemDropDownList =
(DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[0].FindControl("ItemDropDownList");
TextBox rateTextBox =
(TextBox)PurchaseMgmtGridView.Rows[rowIndex].Cells[2].FindControl("RateTextBox");
TextBox qtyTextBox =
(TextBox)PurchaseMgmtGridView.Rows[rowIndex].Cells[3].FindControl("QtyTextBox");
Label totalLabel =
(Label)PurchaseMgmtGridView.Rows[rowIndex].Cells[4].FindControl("TotalLabel");
drCurrentRow = dtCurrentTable.NewRow();
//drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Item"] = itemDropDownList.SelectedItem.ToString();
dtCurrentTable.Rows[i - 1]["ItemUnit"] = itemUnitDropDownList.SelectedItem.ToString();
dtCurrentTable.Rows[i - 1]["Rate"] = rateTextBox.Text;
dtCurrentTable.Rows[i - 1]["Qty"] = qtyTextBox.Text;
dtCurrentTable.Rows[i - 1]["Total"] = totalLabel.Text;
rowIndex++;
}
ViewState["CurrentTable"] = dtCurrentTable;
}
}
else
{
Response.Write("ViewState is null");
}
}
}
}
These codes result something like this
But, as soon as I start to delete one of the rows, it gives me this exception -
This exception is thrown from the SetPreviousData() method from the following code -
DropDownList itemDropDownList = (DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[0].FindControl("ItemDropDownList");
Any idea where I got wrong?
P.S. : Code Updated I [supplied the codes for the list of entities i.e.Item and ItemUnit]

It doesn't look like it's actually the deleting of the row in the GridView that's the issue, but rather something else.
First, two things to note - I can't compile because I don't have the definitions for Item and ItemUnit, so I'm doing this by reading the code. Second, I haven't finished my coffee yet! (Update: My coffee is done!)
It looks like the reference to itemDropDownList in SetPreviousData() is null, so look into why that is. It might be easier to use a foreach loop to iterate through the rows of that DataTable to avoid any issues with 0-based indexes and count-1 comparisons, etc. (Update: It still would be easier, but it's not causing the issue.)
Also, not sure if you mean to do this, but the FindControl statement to get the ItemDropDownList is using rowIndex which is always equal to i. (Update: Again, could help just to clean up the code, but it's not a requirement.)
Start by figuring out what i is when it crashes and seeing if that's what you expect and figure out why the FindControl statement isn't working properly. If it's a 0, it may be trying to reading a header row or something where that Dropdown doesn't exist.
Sorry I can't give you a definitive solution, but hopefully this helps.
Solution:
After getting the full code, it was easier to see what happened. Basically, the PurchaseMgmtGridView_RowDeleting method was deleting the DropdownList from the GridView and then SetPreviousData() was trying to read something that didn't exist. The FindControl statement in SetPreviousData was returning NULL as indicated in the error message, but not for the reason I speculated earlier.
Remove the offending lines from the PurchaseMgmtGridView_RowDeleting method and you'll be all set.
protected void PurchaseMgmtGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
SetRowData();
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
int rowIndex = Convert.ToInt32(e.RowIndex);
if (dt.Rows.Count > 1)
{
dt.Rows.Remove(dt.Rows[rowIndex]);
drCurrentRow = dt.NewRow();
ViewState["CurrentTable"] = dt;
PurchaseMgmtGridView.DataSource = dt;
PurchaseMgmtGridView.DataBind();
// Delete this
//for (int i = 0; i < PurchaseMgmtGridView.Rows.Count - 1; i++)
//{
// PurchaseMgmtGridView.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
//}
SetPreviousData();
}
}
}

I think you trying to access on an object reference that points to null.
Try like this
private void SetPreviousData()
{
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count-1; i++)
{
DropDownList itemDropDownList =
(DropDownList)PurchaseMgmtGridView.Rows[i].Cells[0].FindControl("ItemDropDownList");
DropDownList itemUnitDropDownList =
(DropDownList)PurchaseMgmtGridView.Rows[i].Cells[1].FindControl("ItemUnitDropDownList");
TextBox rateTextBox =
(TextBox)PurchaseMgmtGridView.Rows[i].Cells[2].FindControl("RateTextBox");
TextBox qtyTextBox =
(TextBox)PurchaseMgmtGridView.Rows[i].Cells[3].FindControl("QtyTextBox");
Label totalLabel =
(Label)PurchaseMgmtGridView.Rows[i].Cells[4].FindControl("TotalLabel");
FillItemDropDownList(itemDropDownList);
FillItemUnitDropDownList(itemUnitDropDownList);
if (i < dt.Rows.Count - 1)
{
//itemDropDownList.SelectedValue = dt.Rows[i]["Item"].ToString();
//itemUnitDropDownList.SelectedValue = dt.Rows[i]["ItemUnit"].ToString();
itemDropDownList.ClearSelection();
itemDropDownList.Items.FindByText(dt.Rows[i]["Item"].ToString()).Selected = true;
itemUnitDropDownList.ClearSelection();
itemUnitDropDownList.Items.FindByText(dt.Rows[i]["ItemUnit"].ToString()).Selected = true;
}
rateTextBox.Text = dt.Rows[i]["Rate"].ToString();
qtyTextBox.Text = dt.Rows[i]["Qty"].ToString();
totalLabel.Text = dt.Rows[i]["Total"].ToString();
}
}
}
}
Refer here for Null Reference Exception

Related

How to get cell value from dataTable Asp.Net

I'm creating dynamically data table bound to Grid View. Every row is populated with button. When I determine which button is clicked on the row, I want to get the current value of cell in that row modify her.
Markup:
<asp:GridView ID="GridView2" runat="server"
OnRowDataBound="GridView2_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnTest" runat="server"
CommandName="odzemi"
CssClass="button2"
Font-Bold="True"
Text="-"
Width="100px"
OnClick="btnTest_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
Creating the row:
private void AddNewRecordRowToGrid()
{
int counter;
if (Request.Cookies["kasa"] == null)
counter = 0;
else
{
counter = int.Parse(Request.Cookies["kasa"].Value);
}
counter++;
Response.Cookies["kasa"].Value = counter.ToString();
Response.Cookies["kasa"].Expires = DateTime.Now.AddYears(2);
if (ViewState["Markici"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["Markici"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
HttpCookie cookie = Request.Cookies["Democookie"];
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["FirmaID"] = Request.Cookies["firma"].Value;
drCurrentRow["Godina"] = Request.Cookies["godina"].Value;
drCurrentRow["KasaID"] = Request.Cookies["kasa"].Value;
drCurrentRow["MarkicaID"] = Request.Cookies["kasa"].Value;
drCurrentRow["Datum"] = DateTime.Now;
drCurrentRow["Masa"] = Session["masa39"];
drCurrentRow["VrabotenID"] = Session["New"];
drCurrentRow["Artikal"] = Label3.Text;
drCurrentRow["Cena1"] = Label4.Text;
//this is where i need to make changes
drCurrentRow["Kolicina"] = Label5.text;
drCurrentRow["Smena"] = Session["smena1"];
drCurrentRow["VkIznos"] = Label6.Text;
drCurrentRow["VkDanok"] = Label8.Text;
drCurrentRow["SySDatum"] = DateTime.Now;
drCurrentRow["Vid"] = Label23.Text;
drCurrentRow["Edmera"] = Label10.Text;
drCurrentRow["ArtikalID"] = Label33.Text;
}
//Removing initial blank row
if (dtCurrentTable.Rows[0][0].ToString() == "")
{
dtCurrentTable.Rows[0].Delete();
dtCurrentTable.AcceptChanges();
}
//Added New Record to the DataTable
dtCurrentTable.Rows.InsertAt(drCurrentRow,0);
//storing DataTable to ViewState
ViewState["Markici"] = dtCurrentTable;
//binding Gridview with New Row
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
}
}
}
//determine which button is clicked in data Table
//and here
protected void btnTest_Click(object sender, EventArgs e)
{
DataTable dtCurrentTable = (DataTable)ViewState["Markici"];
var clickedRow = ((Button)sender).NamingContainer as GridViewRow;
var clickedIndex = clickedRow.RowIndex;
count--;
decimal noofcount = count;
//and here i want to get current value and modify her.
dtCurrentTable.Rows[clickedIndex]["Kolicina"] = "88";
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
}
If the only problem is that you don't know how to read the old value as noted here:
//and here i want to get current value and modify her.
dtCurrentTable.Rows[clickedIndex]["Kolicina"] = "88";
then this works:
object oldValue = dtCurrentTable.Rows[clickedIndex]["Kolicina"];
// cast/convert it to whatever it is
or (what i prefer):
string old = dtCurrentTable.Rows[clickedIndex].Field<string>("Kolicina");
int oldValue = int.Parse(old); // in case that you don't know
int newValue = oldValue + count; // just an example
dtCurrentTable.Rows[clickedIndex].SetField("Kolicina", newValue.ToString());
I'm using the Field/SetField extension methods for DataRow because it is strongly typed and even supports nullable types.
By the way, why do you store ints as strings?

Save checked row of one dataGrid into another dataGrid

I have a simple datagrid which Stores the data returned in json format in it. I have added unbound checkbox column to it. Now I want to Store only the checked rows in another datagrid. How should I proceed.
My Code
protected void BtnSave_Click(object sender, EventArgs e)
{
foreach (DataGridItem item in this.gv1.Items)
{
CheckBox chkBox =
(CheckBox)item.FindControl("ChkRows");
//If it's selected then add it to our new Datagrid
if (chkBox != null && chkBox.Checked)
{
//save
}
}
}
datasource for 1st grid
SearchAPIRequest.defaultApiKey = "samplekey";
SearchAPIRequest request = new SearchAPIRequest(rawName: txtUser.Text);
try
{
SearchAPIResponse response = request.Send();
DataTable dt = new DataTable();
dt.Columns.Add("Website");
dt.Columns.Add("first");
dt.Columns.Add("last");
dt.Columns.Add("jobs");
dt.Columns.Add("dobs");
dt.Columns.Add("educations");
dt.Columns.Add("addresses");
dt.Columns.Add("images");
dt.Columns.Add("URL");
for (int i = 0; i < response.Records.Count; i++)
{
DataRow dr = dt.NewRow();
dr["Website"] = response.Records[i].Source.Domain;
dr["First"] = response.Records[i].Names[0].First;
dr["Last"] = response.Records[i].Names[0].Last;
dr["jobs"] = response.Records[i].Jobs.Count > 0 ? response.Records[i].Jobs[0].Display: "";
dr["dobs"] = response.Records[i].DOBs.Count > 0 ? response.Records[i].DOBs[0].DateRange.Start.ToString() : "";
dr["images"] = response.Records[i].Images.Count> 0 ? response.Records[i].Images[0].Url:"";
dr["educations"] = response.Records[i].Educations.Count > 0 ? response.Records[i].Educations[0].Display : "";
dr["addresses"] = response.Records[i].Addresses.Count > 0 ? response.Records[i].Addresses[0].Display: "";
dr["URL"] = response.Records[i].Source.Url;
dt.Rows.Add(dr);
}
gv1.DataSource = dt;// response.Records[0].AllFields.ToList();
gv1.DataBind();

How do I extract data from a dynamicly created table ASP.NET

I got table, generated by this code (I know it looks bad but it just as a test):
protected void Gen_Load(object sender, EventArgs e)
{
List<string> ParamList = new List<string>();
ParamList.Add("Perforation");
ParamList.Add("Top of perforation");
ParamList.Add("Bottom of perforation");
ParamList.Add("Well radius");
for (int i = 0; i < 4; i++)
{
TableRow row1=new TableRow();
TableCell cell1=new TableCell();
cell1.BorderColor=System.Drawing.Color.DarkGray;
cell1.BorderWidth=2;
cell1.Font.Size = 11;
cell1.Text=ParamList.ElementAt(i);
TableCell cell2 = new TableCell();
cell2.BorderColor=System.Drawing.Color.DarkGray;
cell2.BorderWidth=2;
cell2.Width = 200;
TextBox text1 = new TextBox();
text1.ID = "txtb_1" + i;
text1.Width = cell2.Width;
text1.Height = cell2.Height;
cell2.Controls.Add(text1);
TableCell cell3 = new TableCell();
cell3.BorderColor=System.Drawing.Color.DarkGray;
cell3.BorderWidth=2;
cell3.Width = 200;
DropDownList dlist = new DropDownList();
dlist.ID = "dlist_1" + i;
ListItem li1 = new ListItem("m");
ListItem li2 = new ListItem("ft");
// if (i != 0)
// {
dlist.Items.Add(li1);
dlist.Items.Add(li2);
// }
dlist.Width = cell3.Width;
dlist.Height = cell3.Height;
cell3.Controls.Add(dlist);
row1.Cells.Add(cell1);
row1.Cells.Add(cell2);
row1.Cells.Add(cell3);
row1.ID = "id" + i;
ParamTable.Rows.Add(row1);
}
}
So how do I can get data from dropdownlist and textbox elements on it? I assume that I could use elements ID somehow to call them, but I can't find any example.
UPD: aspx
<asp:Table CssClass="span9" style="margin-top:2px; margin-bottom:5px;" ID="ParamTable" runat="server">
<asp:TableHeaderRow >
<asp:TableHeaderCell Font-Size="Medium" BorderColor="DarkGray" BorderWidth="2px" >Parameters</asp:TableHeaderCell>
<asp:TableHeaderCell Font-Size="Medium" BorderColor="DarkGray" BorderWidth="2px" >Value</asp:TableHeaderCell>
<asp:TableHeaderCell Font-Size="Medium" BorderColor="DarkGray" BorderWidth="2px" >Units</asp:TableHeaderCell>
</asp:TableHeaderRow>
<asp:TableRow >
</asp:TableRow>
</asp:Table>
See below code to get the value of each row :
for (int i = 0; i < ParamTable.Rows.Count; i++)
{
var textBoxValue = ((TextBox)ParamTable.Rows[i].Cells[1].FindControl("txtb_1" + i)).Text;
var dropDownValue = ((DropDownList)ParamTable.Rows[i].Cells[2].FindControl("dlist_1" + i)).SelectedItem.Text;
}
Note: I don't store values in any list. You can use POCO/Property class as per your requirement.
Update:
Remove <asp:TableRow ></asp:TableRow> from aspx and update forloop as mentioned below:
for (int i = 0; i < ParamTable.Rows.Count - 1; i++)
{
var textBoxValue = ((TextBox)ParamTable.Rows[i].Cells[1].FindControl("txtb_1" + i)).Text;
var dropDownValue = ((DropDownList)ParamTable.Rows[i].Cells[2].FindControl("dlist_1" + i)).SelectedItem.Text;
}

Sorting option, what am I missing?

Sorting works fine, if I use the local IIS in windows, but not working online.. Please help!
Here is the code:
AllowPaging="false" AllowSorting=true
ShowHeaderWhenEmpty="True"
onrowdeleting="gridvwAssessments_RowDeleting"
onselectedindexchanged="gridvwAssessments_SelectedIndexChanged"
onpageindexchanging="gridvwAssessments_PageIndexChanging"
OnRowEditing="EditAssessment" OnRowUpdating="UpdateAssessment" OnRowCancelingEdit="CancelEdit"
onsorting="gridvwAssessments_Sorting" >
<Columns>
<asp:TemplateField ItemStyle-Width="100px" HeaderText="NAME" SortExpression="Res_Name">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" Text='<%# Eval("Res_Name")%>'></asp:Label>
<asp:HiddenField ID="assessmentId" runat="server" Value='<%# Eval("Id")%>' />
</ItemTemplate>
</asp:TemplateField>
CSS:
protected void gridvwAssessments_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = ((DataTable)((GridView)sender).DataSource);
Image sortImage = new Image();
if (dt != null)
{
//Sort the data.
if (Session["Assessment_SortDir"] != null)
{
if (Session["Assessment_SortDir"].ToString() == "ASC")
{
Session["Assessment_SortDir"] = "DESC";
sortImage.ImageUrl = "Images\\Desc.gif";
}
else
{
Session["Assessment_SortDir"] = "ASC";
sortImage.ImageUrl = "Images\\Asc.gif";
}
}
else
{
Session["Assessment_SortDir"] = "ASC";
sortImage.ImageUrl = "Images\\Asc.gif";
}
dt.DefaultView.Sort = e.SortExpression + " " + Session["Assessment_SortDir"].ToString();
gridvwAssessments.DataSource = dt;
gridvwAssessments.DataBind();
int columnIndex = 0;
foreach (DataControlFieldHeaderCell headerCell in gridvwAssessments.HeaderRow.Cells)
{
if (headerCell.ContainingField.SortExpression == e.SortExpression)
{
columnIndex = gridvwAssessments.HeaderRow.Cells.GetCellIndex(headerCell);
}
}
gridvwAssessments.HeaderRow.Cells[columnIndex].Controls.Add(sortImage);
}
}
I think the issue is with dt.Defaultview.Sort.
Using DefaultView has always had me run into sorting issues. I usually try to create a new view instead. You may want to give it a try...
DataView dv = new DataView(dt);
dv.Sort = String.Format("{0} {1}", e.SortExpression, Session["Assessment_SortDir"]);
gridvwAssessments.DataSource = dv;
// or you can use dv.ToTable(...);

Populating dynamic table in asp.net?

I would really appreciate your help on this. This is my problem:
I have a ArrayList of product objects. Each product has a id, name and a supplier.
When I iterate the arraylist and creates a table to put this value into cells I come to the problem that a product can have more than one supplier. If this is the case the id and name are the same but with a different supplier in the arraylist.
My code so far takes care of this by creating empty cells for id and name and put the other supplier in a new cell.
But, it doesn't look good to create new rows for every supplier. What I want is that if a product has more than one supplier I want all the suppliers in the same cell on the row for the product id.
string id = string.Empty;
int count = 0;
public void CreateResultTable(ArrayList result)
{
TableRow row;
TableCell cell;
if (result != null && result.Count > 0)
{
foreach (Item item in result)
{
if (count == 0)
{
row = new TableRow();
id = item.id;
cell = new TableCell();
cell.Text = item.id;
row.Cells.Add(cell);
cell = new TableCell();
cell.Text = item.product;
row.Cells.Add(cell);
cell = new TableCell();
ArrayList levList = item.suppliers;
if (levList != null)
{
string lev = string.Empty;
for (int i = 0; i < levList.Count; i++)
{
lev += levList[i];
}
cell.Text = lev;
row.Cells.Add(cell);
}
else
cell.Text = string.Empty;
row.Cells.Add(cell);
count++;
}
else if (id != item.id)
{
row = new TableRow();
id = item.id;
cell = new TableCell();
cell.Text = item.id;
row.Cells.Add(cell);
cell = new TableCell();
cell.Text = item.product;
row.Cells.Add(cell);
cell = new TableCell();
ArrayList levList = item.suppliers;
if (levList != null)
{
string lev = string.Empty;
for (int i = 0; i < levList.Count; i++)
{
lev += levList[i];
}
cell.Text = lev;
}
else
cell.Text = string.Empty;
row.Cells.Add(cell);
}
else
{
row = new TableRow();
cell = new TableCell();
cell.Text = string.Empty;
row.Cells.Add(cell);
cell = new TableCell();
cell.Text = string.Empty;
row.Cells.Add(cell);
cell = new TableCell();
ArrayList levList = item.suppliers;
if (levList != null)
{
string lev = string.Empty;
for (int i = 0; i < levList.Count; i++)
{
lev += levList[i];
}
cell.Text = lev;
row.Cells.Add(cell);
}
else
cell.Text = string.Empty;
row.Cells.Add(cell);
}
SearchResultLev.Rows.Add(row);
}
SearchResultLev.Visible = true;
SearchResult.Visible = false;
NoSearchResult.Visible = false;
}
else
{
SearchResultLev.Visible = false;
SearchResult.Visible = false;
NoSearchResult.Visible = true;
}
}
Instead of generating a table in code-behind use a GridView.
I've a sample here which uses GridView and a Repeater inside the GridView's Item Template.
The repeater spits out a unbounded list for each supplier.
Markup:
<asp:GridView ID='GridView1' runat='server' AutoGenerateColumns='false'>
<Columns>
<asp:BoundField HeaderText='Product ID' DataField='ID' />
<asp:BoundField HeaderText='Name' DataField='Name' />
<asp:TemplateField HeaderText='Suppliers'>
<ItemTemplate>
<asp:Repeater DataSource='<%# Bind("Suppliers") %>' runat="server" ID='Repeater1'>
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li><%# Eval("Name") %></li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And code to bind the data (the type definition are below)
GridView1.DataSource = new List<TestProduct>
{
new TestProduct
{
Name = "Test",
ID = "1",
Suppliers = new List<TestSupplier>
{
new TestSupplier { Name="Supplier1" },
new TestSupplier { Name = "Supplier2" },
new TestSupplier { Name =" A very long supplier name"}
}
}
};
GridView1.DataBind();
I've used sample TestProduct and TestSuppliers,
public class TestProduct
{
public String ID { get; set; }
public String Name { get; set; }
public List<TestSupplier> Suppliers { get; set; }
}
public class TestSupplier { public String Name { get; set; }}
sample output:
You can use a Hashtable here:
Hashtable htProductCell = new Hashtable();
if (!htProductCell.Contains(item.product))
{
//add a new row for the item
htProductCell.Add(item.product, cell);
}
else
{
TableCell cell = (TableCell)htProductCell[item.product];
ArrayList levList = item.suppliers;
if (levList != null)
{
string lev = string.Empty;
for (int i = 0; i < levList.Count; i++)
{
lev += levList[i];
}
cell.Text += lev;
row.Cells.Add(cell);
}
}

Categories

Resources