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;
}
Related
I Created a application which will map the data and save the Data fields. For that first row in my GridView I added new HearerRow with dropdownlist.
Below is my code which I have attached.
My HTML Page code:
<asp:GridView ID="gvDataMapping" runat="server" AutoGenerateColumns="false">
</asp:GridView>
And Code Behind:
for (int i = 0; i < dtValues.Columns.Count; i++)
{
BoundField boundfield = new BoundField();
boundfield.DataField = dtValues.Columns[i].ColumnName.ToString();
boundfield.HeaderText = dtValues.Columns[i].ColumnName.ToString();
gvDataMapping.Columns.Add(boundfield);
}
gvDataMapping.DataSource = dtValues;
gvDataMapping.DataBind();
GridViewRow HeaderGridRow = new GridViewRow(0, 0, DataControlRowType.Header,
DataControlRowState.Insert);
DropDownList ddlFieldValues;
TableCell HeaderCell;
foreach (DataColumn dc in dtValues.Columns)
{
ddlFieldValues = new DropDownList();
ddlFieldValues.ID = "FieldValues";
ddlFieldValues.DataSource = (DataTable)Session["WorkItemTypeField"];
ddlFieldValues.DataTextField = "FieldName";
ddlFieldValues.DataValueField = "FieldID";
ddlFieldValues.DataBind();
ddlFieldValues.Items.Insert(0, new ListItem("", "0"));
HeaderCell = new TableCell();
HeaderCell.Controls.Add(ddlFieldValues);
HeaderGridRow.Cells.Add(HeaderCell);
}
gvDataMapping.DataSource = dtValues;
gvDataMapping.DataBind();
gvDataMapping.Visible = true;
lblDataMapping.Visible = true;
gvDataMapping.Controls[0].Controls.AddAt(1, HeaderGridRow);
See the Click here to view screen displays the output of above code . While clicking Save am not getting the GridView Header DropDowmList its showing null using below code.
GridViewRow gvrow2 = gvDataMapping.HeaderRow;
foreach (GridViewRow row in gvDataMapping.Rows)
{
for (int i = 0; i < gvDataMapping.Columns.Count; i++)
{
String header = gvDataMapping.Columns[i].HeaderText; //gets column name
DropDownList cellText = ((DropDownList)gvrow2.Cells[i].FindControl("FieldValues")); //Not getting the DDL returns null
}
}
How to get the GridView Header row dropdownlist values in Save click event?
No guarantees, because I haven't tried this myself, but what about this code?
GridViewRow gvrow1 = GrdDynamic1.HeaderRow;
foreach (GridViewRow row in GrdDynamic1.Rows)
{
for (int i = 0; i < GrdDynamic1.Columns.Count; i++)
{
String header = GrdDynamic1.Columns[i].HeaderText;
DropDownList cellText = ((DropDownList)gvrow1.Cells[i].FindControl("FieldValues"));
}
}
It looks as if you're looking for the drop down list in the right column, but not the right row: you're looking in the data row, rather than the header row gvrow1.
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?
Edit for clarity: I know the code has 2 columns, one for title and one for date, I am trying to change the code so it displays 3 events per row.
I am new to development and I am trying to take an ASP control used in a Sitefinity 6.1 website that currently takes data from our SQL database and outputs it into a single column and instead produce an output in 3 columns.
The .ascx looks like this
<div style="margin:10px">
<asp:MultiView ID="mvEvents" runat="server" ActiveViewIndex="0">
<asp:View ID="viewDefault" runat="server">
<asp:Table ID="tblEvents" runat="server" CellPadding="5">
</asp:Table>
</asp:View>
<asp:View ID="viewList" runat="server">
<asp:Table ID="tblEventsList" runat="server" CellPadding="5">
</asp:Table>
</asp:View>
</asp:MultiView>
</div>
The PageLoad and BuildEvents portions of the .ascx.cs code look like this
protected void Page_Load(object sender, EventArgs e)
{
try
{
CalendarDataContext db = new CalendarDataContext();
var evt = db.CalendarEvents(NumberToDisplay, Department);
foreach (CalendarEventsResult Evt in evt)
{
if (Department == "List")
{
BuildEventsList(Evt.event_name, Evt.event_start_date, Evt.event_idn, Evt.information_id);
}
else
{
BuildEvents(Evt.event_name, Evt.event_start_date, Evt.event_idn, Evt.information_id);
}
}
return;
}
catch(Exception ex)
{
}
}
protected void BuildEvents(string EvtTitle, DateTime EvtStart, int EvtIdn, int EvtInfoIdn)
{
//EvtInfoIdn shows Event Description without location. EvtInfoIdn - 1 shows location information. changing the href to eventInfoId
int EvtInfoId = EvtInfoIdn - 1;
TableRow tr = new TableRow();
tr.VerticalAlign = VerticalAlign.Top;
tr.HorizontalAlign = HorizontalAlign.Center;
TableCell tcTitle = new TableCell();
TableCell tcStart = new TableCell();
StringBuilder sb = new StringBuilder();
sb.AppendLine(ShortMonth(EvtStart.Month));
sb.AppendLine(EvtStart.Day.ToString());
tr.VerticalAlign = VerticalAlign.Bottom;
tr.Height = Unit.Pixel(80);
Literal litDate = new Literal();
litDate.Text = "<div class='EventDate'>" + sb.ToString() + "</div>";
tcStart.Controls.Add(litDate);
Literal litTitle = new Literal();
litTitle.Text = #"<div class='EventTitle'><a style='text-decoration:none;' href='http://events.website.edu/EventList.aspx?view=EventDetails&eventidn=" + EvtIdn.ToString().Trim() + "&information_id=" + EvtInfoId + "&type=&rss=rss'>";
litTitle.Text = litTitle.Text + EvtTitle + "</a></div>";
tcTitle.Controls.Add(litTitle);
tr.Cells.Add(tcStart);
tr.Cells.Add(tcTitle);
tblEvents.Rows.Add(tr);
}
I have tried adding a ColumnSpan = "3" attribute to the ascx file and also tried adding the ColumnSpan to tcStart and tcTitle in the cs file as well in addition to trying to redesign the ascx in design mode and nothing I have though of has worked. I realize this is likely an easy fix, but I am new to C# programming. I appreciate any help provided.
Try the following -- n.b. I haven't been able to test fully as I haven't mocked up your bespoke classes, e.g. CalendarDataContext.
The basic premise is that the CalandarEvents collection is processed in batches of 3 (or whatever number you choose) and that the BuildEvents method now is broken down into smaller parts, each with their own responsibility, which should help with maintenance going forward.
protected void Page_Load(object sender, EventArgs e)
{
try
{
CalendarDataContext db = new CalendarDataContext();
var evt = db.CalendarEvents(NumberToDisplay, Department);
if (Department == "List")
{
foreach (CalendarEventsResult cer in evt)
{
BuildEventsList(cer.event_name, cer.event_start_date, cer.event_idn, cer.information_id);
}
}
else
{
// Depending what type evt is may depend on how to convert to the List.
// This assumes that it supports IEnumerable (like DataTable)
List<CalendarEventsResult> events = evt.AsEnumerable().ToList();
// Rather than hard-coding, read this from config or database
// to allow easier changing to a different number of events per row?
int numberOfEventsPerRow = 3;
// loop increments in steps of 3 (numberOfEventsPerRow)
for (int rowNumber = 0; rowNumber < events.Count; rowNumber += numberOfEventsPerRow)
{
// use Linq to pick out the subset of Events to process
List<CalendarEventsResult> queryEvents = events
.Skip(numberOfEventsPerRow * rowNumber)
.Take(numberOfEventsPerRow).ToList<CalendarEventsResult>();
// Build a row using that subset
TableRow tr = buildRow(queryEvents, numberOfEventsPerRow);
// Add it to the table
tblEvents.Rows.Add(tr);
}
}
}
catch (Exception ex)
{
// this just suppresses any exceptions. Better to fix issues at source.
}
}
private TableRow buildRow(List<CalendarEventsResult> events, int eventsPerRow)
{
TableRow tr = new TableRow();
// Can these be added to CSS?
tr.HorizontalAlign = HorizontalAlign.Center;
tr.VerticalAlign = VerticalAlign.Bottom;
tr.Height = Unit.Pixel(80);
TableCell tc;
// for our event subset, build a pair of cells for each Event,
// adding them to a row
foreach (var evt in events)
{
tc = BuildEventDate(evt);
tr.Cells.Add(tc);
tc = BuildEventTitle(evt);
tr.Cells.Add(tc);
}
// If we're dealing with a partial row, i.e. only 1 or 2 Events,
// pad the row with empty cells.
if (events.Count < eventsPerRow)
{
tc = BuildEmptyCell(eventsPerRow - events.Count);
tr.Cells.Add(tc);
}
return tr;
}
private TableCell BuildEventDate(CalendarEventsResult evt)
{
TableCell tc = new TableCell();
Literal litDate = new Literal();
//String.Format should suffice c.f. StringBuilder
litDate.Text = String.Format("<div class='EventDate'>{0}{1}</div>", ShortMonth(evt.Month), evt.Day.ToString());
tc.Controls.Add(litDate);
return tc;
}
private TableCell BuildEventTitle(CalendarEventsResult evt)
{
TableCell tc = new TableCell();
int evtInfoId = evt.information_id - 1;
Literal litTitle = new Literal();
// n.b. hard-coded URL doesn't look good for ease of maintenance (move to config or CalendarEventsResult?)
litTitle.Text = String.Format(#"<div class='EventTitle'><a style='text-decoration:none;' href='http://events.website.edu/EventList.aspx?view=EventDetails&eventidn={0}&information_id={1}&type=&rss=rss'>{2}</a></div>",
evt.event_idn.ToString().Trim(), evtInfoId, evt.event_name);
tc.Controls.Add(litTitle);
return tc;
}
private TableCell BuildEmptyCell(int numberOfEvents)
{
// Define as const rather than having unexplained "2" hard-coded.
const int spanPerEvent = 2;
TableCell tc = new TableCell();
tc.ColumnSpan = spanPerEvent * numberOfEvents;
tc.Text = "";
return tc;
}
}
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
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);
}
}