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(...);
Related
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" />
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?
protected void RadTreeView1_NodeClick(object sender, RadTreeNodeEventArgs e)
{
if (e.Node.Level != 0)
{
// value of the selected child node
string text = e.Node.Value;
}
}
here i am getting text value always null...please help me
In radtree node click event i tried to get the node value
<telerik:RadTreeView ID="RadTreeView1" runat="server" Width="300px" Height="100px" Skin="Metro" OnNodeClick="RadTreeView1_NodeClick" AutoPostBack="true" OnClientNodeClicked="">
<DataBindings>
<telerik:RadTreeNodeBinding Expanded="True"></telerik:RadTreeNodeBinding>
</DataBindings>
</telerik:RadTreeView>
private void BindGrid()
{
try
{
DataView dv;
string json = class.HttpGet(url + "Services/Product.svc/ProductCategorySD1");
json = Regex.Unescape(json);
dt = (DataTable)JsonConvert.DeserializeObject(json.Trim(new Char[] { ' ', '"', '.' }), typeof(DataTable));
dv = dt.DefaultView;
grid.DataSource = dv;
grid.DataBind();
RadTreeView1.DataTextField = "ProductCategoryName";
RadTreeView1.DataFieldID = "ProductCategoryRowId";
RadTreeView1.DataFieldParentID = "ParentProductCategoryRowId";
RadTreeView1.DataSource = dt;
RadTreeView1.DataBind();
}
catch (Exception Err)
{
}
finally { }
}
treebinded perfectly..........................
You have to explicitily set the DataValueField property of your RadTreeView and then perform DataBind operation:
RadTree1.DataTextField = "MyTextColumn"
// following line is absent from supplied sample in the OP
RadTree1.DataValueField = "MyValueColumn"
RadTree1.DataFieldID = "MyID"
RadTree1.DataFieldParentID = "MyParentID"
RadTree1.DataSource = ds
RadTree1.DataBind()
In the sample code provided in the OP you are only setting DataTextField. My guess is if you do sth like:
string text = e.Node.Text;
you will successfully read the text of RadTreeNode.
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
How to start a dropdownlist with an empty values?
Does anyone have any suggestions as to how I can get round this
problem, aside from creating a blank manager entry in the table, which
is obviously not ideal!
Many thanks!
ASPX PAGE
<asp:Repeater ID="GeneralRepeater" runat="server"
OnItemDataBound="GeneralRepeater_OnItemDataBound">
<ItemTemplate>
<tr>
<td>
DxPoc:
<asp:DropDownList ID="GeneralDDL" DataTextField="DiagnosisCode"
DataValueField="DiagnosisCode" runat="server" />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
CODE BEHIND:
protected void GeneralRepeater_OnItemDataBound(object sender,
RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList myDDL = (DropDownList)e.Item.FindControl("GeneralDDL");
Diagnosis oDiagnosis = new Diagnosis();
DataView dv = new DataView(oDiagnosis.GetDiagnosis());
myDDL.DataSource = dv;
myDDL.DataTextField = "DiagnosisCode";
myDDL.DataValueField = "DiagnosisCode";
myDDL.DataBind();
}
}
You will want to insert code like this into your ItemDataBound function, after the DDL has been databound:
ListItem LI = New ListItem("(empty item)", "0");
myDDL.Items.Insert(0, LI);
myDDL.SelectedValue = "0";
Use the following:
dropDownList.DataSource = AddHeaderItem
(
list.ToDictionary
(instance => instance.Key.ToString(), instance => instance.Value),
true,
"Please Select an Item..."
);
// Add a header item to a Dictionary ..
public static Dictionary<String, String> AddHeaderItem
(Dictionary<String, String> items, Boolean addHeaderItem,
String headerItemText = "")
{
var headerItem = new Dictionary<String, String>();
if (addHeaderItem)
{
headerItem["-1"] = headerItemText;
}
//else { }
return headerItem.Concat(items).ToDictionary
(item => item.Key, item => item.Value);
}
Are you looking for this?
Alter your listitem by setting AppendDataBoundItems="true"
<asp:DropDownList ID="GeneralDDL" AppendDataBoundItems="true" DataTextField="DiagnosisCode" DataValueField="DiagnosisCode"
runat="server">
<asp:ListItem Text="--Select--" Value=""></asp:ListItem>
</asp:DropDownList>