I met the error of Cannot find column CustomerItemNoAppend. when I clicked on my search button.
Condition: If user is not internal, hide 2 columns. My current query did not involve the column CustomerItemNoAppend and ManufacturerItemNoAppend.
Suggested by #tetsuya-yamamoto, I would not meet the error of Cannot find column when getColumnSafe is used.
public IQueryable GetAllInventorySummary()
{
var query = from summary in dataContext.Q_TBL_INVENTORY_SUMMARIES
group summary by new
{
poaItemNo = summary.POAItemNo,
customerItemNo = summary.CustomerItemNo,
manufacturerItemNo = summary.ManufacturerItemNo,
itemDescription = summary.ItemDescription,
uom = summary.UOM,
} into grp
select new
{
POAItemNo = grp.Key.poaItemNo,
CustomerItemNo = grp.Key.customerItemNo,
ManufacturerItemNo = grp.Key.manufacturerItemNo,
ItemDescription = grp.Key.itemDescription,
OnHandQty = grp.Sum(s => s.OnHandQty),
UOM = grp.Key.uom,
InventoryLocationNo = "All",
};
return query;
}
Main method:
if (profile.UserInternal != 'Y')
{
RadGrid1.DataSource = inventory.GetAllInventorySummary(profile.CompanyID);
RadGrid1.MasterTableView.GetColumnSafe("CustomerItemNoAppend").Visible = false;
RadGrid1.MasterTableView.GetColumnSafe("ManufacturerItemNoAppend").Visible = false;
}
else
{
RadGrid1.DataSource = inventory.GetAllInventorySummary();
RadGrid1.MasterTableView.GetColumnSafe("CustomerItemNo").Visible = false;
RadGrid1.MasterTableView.GetColumnSafe("ManufacturerItemNo").Visible = false;
}
}
else
{
if (profile.UserInternal != 'Y')
{
RadGrid1.DataSource = inventory.GetInventorySummaryByLocation(InventoryLocation.SelectedValue);
RadGrid1.MasterTableView.GetColumnSafe("CustomerItemNoAppend").Visible = false;
RadGrid1.MasterTableView.GetColumnSafe("ManufacturerItemNoAppend").Visible = false;
}
else
{
RadGrid1.DataSource = inventory.GetInventorySummaryByLocation(InventoryLocation.SelectedValue);
RadGrid1.MasterTableView.GetColumnSafe("CustomerItemNo").Visible = false;
RadGrid1.MasterTableView.GetColumnSafe("ManufacturerItemNo").Visible = false;
}
}
Search Button:
protected void btnSearch_Click(object sender, EventArgs e)
{
InventoryProvider inventory = new InventoryProvider();
GetInventorySummary();
DataProvider.CloseConnectionDB();
RadGrid1.DataBind();
}
Telerik Radgrid columns:
<telerik:GridBoundColumn HeaderText="Customer Item No." UniqueName="CustomerItemNo"
HeaderStyle-Width="150px" SortExpression="CustomerItemNo" DataField="CustomerItemNo"
DataType="System.String" />
<telerik:GridBoundColumn HeaderText="Manufacturer Item No." UniqueName="ManufacturerItemNo"
SortExpression="ManufacturerItemNo" DataField="ManufacturerItemNo" DataType="System.String" />
<telerik:GridBoundColumn HeaderText="Customer Item No. Appended" UniqueName="CustomerItemNoAppend"
HeaderStyle-Width="150px" SortExpression="CustomerItemNoAppend" DataField="CustomerItemNoAppend"
DataType="System.String" />
<telerik:GridBoundColumn HeaderText="Manufacturer Item No. Appended" UniqueName="ManufacturerItemNoAppend"
HeaderStyle-Width="150px" SortExpression="ManufacturerItemNoAppend" DataField="ManufacturerItemNoAppend"
DataType="System.String" />
Related
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?
I have:
1 Datatable - EmployeeAccess &
1 View - View_HCM
Both have the same column (EmpNo), View_HCM have 1000+ data where EmployeeAccess have only 4 data.
View_HCM has email address field and EmployeeAccess has none. I need to get email address from View_HCM according to the 4 data.
public List<EmployeeAccess> EmployeeAccess2()
{
EmployeeAccess EA = new EmployeeAccess();
View_HCM VH = new View_HCM();
var x = from b in contxt.View_HCM
where b.EmpNo == EA.EmpNo
select b.EmailAddress;
return x.ToList();
}
I'm getting this error:
Cannot implicitly convert type 'Systems.Generic.Collections.String<string>' to ... '< list >'
Your return type is wrong.
To fix the errror change the returned type:
public List<string> EmployeeAccess2()
{
EmployeeAccess EA = new EmployeeAccess();
View_HCM VH = new View_HCM();
var x = from b in contxt.View_HCM
where b.EmpNo == EA.EmpNo
select b.EmailAddress;
return x.ToList();
}
And to show the email address in the gridview you can do like this
Define a class with a single named field:
public class EmailRecord
{
public string EmailAddress{ get; set; }
}
public List<EmailRecord> EmployeeAccess2()
{
EmployeeAccess EA = new EmployeeAccess();
View_HCM VH = new View_HCM();
var x = from b in contxt.View_HCM
where b.EmpNo == EA.EmpNo
select new EmailRecord
{
EmailAddress = b.EmailAddress
};
return x.ToList();
}
Bind your grid
gridEmployeeAccess.DataSource = TAClass.EmployeeAccess2(); gridEmployeeAccess.DataBind();
In aspx:
<asp:GridView ID="gridEmployeeAccess" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="EmailAddress" headertext="Email Address"/>
</Columns>
</asp:GridView>
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
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(...);
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);
}
}