Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

GridViewUpdateEventArgs.NewValues.Count = 0 ? 1

Status
Not open for further replies.

jmeckley

Programmer
Jul 15, 2002
5,269
US
I'm experimenting with a GridViewXEventArgs. When Updating/Deleting the Keys and Values collection are empty. I can't figure out why.

here is a simple setup I created to reproduce my problem.
ASPX
Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="HardwareInventory.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]

<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml"[/URL] >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView ID="MyGridView" runat="server" AutoGenerateColumns="false" DataKeyNames="Id">
            <Columns>
                <asp:BoundField HeaderText="Full Name" DataField="Name" />
                <asp:BoundField HeaderText="DOB" DataField="BirthDate" HtmlEncode="false" DataFormatString="{0:D}" />
                <asp:CommandField ButtonType="button" ShowEditButton="true" ShowDeleteButton="true" />
            </Columns>
        </asp:GridView>
    </form>
</body>
</html>

Code Behind
Code:
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace HardwareInventory
{
    public partial class WebForm1 : Page
    {
        private List<Person> data
        {
            get
            {
                List<Person> toReturn = (List<Person>)ViewState["data"];
                if (toReturn == null)
                {
                    toReturn = new List<Person>();
                    toReturn.Add(new Person(1, "John", new DateTime(1950, 1, 1)));
                    toReturn.Add(new Person(2, "Jane", new DateTime(1960, 2, 2)));
                    toReturn.Add(new Person(3, "Mary", new DateTime(1970, 3, 3)));
                }
                return toReturn;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            this.MyGridView.RowEditing += new GridViewEditEventHandler(MyGridView_RowEditing);
            this.MyGridView.RowUpdating += new GridViewUpdateEventHandler(MyGridView_RowUpdating);
            this.MyGridView.RowDeleting += new GridViewDeleteEventHandler(MyGridView_RowDeleting);
            this.MyGridView.RowCancelingEdit += new GridViewCancelEditEventHandler(MyGridView_RowCancelingEdit);

            if(!this.IsPostBack)
            {
                this.BindGrid();
            }
        }

        void MyGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            this.MyGridView.EditIndex = -1;
            this.BindGrid();
        }

        void MyGridView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.MyGridView.EditIndex = e.NewEditIndex;
            this.BindGrid();
        }

        void MyGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int index = this.data.FindIndex(delegate(Person p) 
            { 
                return [COLOR=red]e.Keys["Id"][/color].Equals(p.Id); 
            });
            this.data.RemoveAt(index);
            this.BindGrid();
        }

        void MyGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            Person person = this.data.Find(delegate(Person p) 
            { 
                return [COLOR=red]e.Keys["Id"][/color].Equals(p.Id); 
            });
            person.Name = (string)[COLOR=red]e.NewValues["Name"][/color];
            person.BirthDate = (DateTime)[COLOR=red]e.NewValues["BirthDate"][/color];
            this.BindGrid();
        }

        private void BindGrid()
        {
            this.MyGridView.DataSource = data;
                this.MyGridView.DataBind();
        }
    }

    public class Person
    {
        private int id;
        private string name;
        private DateTime birthDate;

        public int Id { get { return this.id; } }
        public string Name
        {
            get { return this.name; }
            set { this.name = value; }
        }
        public DateTime BirthDate
        {
            get { return this.birthDate; }
            set { this.birthDate = value; }
        }
        public int Age { get { return DateTime.Today.Year - this.BirthDate.Year; } }

        public Person(int id, string name, DateTime birthDate)
        {
            this.id = id;
            this.name = name;
            this.birthDate = birthDate;
        }
    }
}
The red text is where the NullReferenceException is thrown because the Key/NewValue count is 0.

any ideas?

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
It looks as though you can't use keys if you are using templates fields or if you are not using the built in data controls. I haven't had time to verify this but that seemed to be the case from reading this.


____________________________________________________________
Mark,
[URL unfurl="true"]http://aspnetlibrary.com[/url]

Need help finding an answer? Try the Search Facility or read FAQ222-2244.
 
I seems templatefields are ok to extact a value from if [tt]<%#Bind("MyProperty")[/tt] is used. This works until I attempt to dyanimcally load a DropDownList.

so this works (I added the food property to person to test dropdowns)
Code:
<asp:TemplateField HeaderText="Favorite Food" SortExpression="Food">
    <EditItemTemplate>
        <asp:DropDownList ID="FoodDropDownList" runat="server" SelectedValue='<%# Bind("Food") %>'>
            <asp:ListItem Text="[ Select ]" Value="" />
            <asp:ListItem Text="Apple" Value="Apple" />
            <asp:ListItem Text="Avacado" Value="Avacado" />
            <asp:ListItem Text="Bananna" Value="Bananna" />
            <asp:ListItem Text="Mango" Value="Mango" />
            <asp:ListItem Text="Orange" Value="Orange" />
        </asp:DropDownList>
    </EditItemTemplate>
    <ItemTemplate><%# Eval("Food") %></ItemTemplate>
</asp:TemplateField>

but this does not work. No excpetions but it cannot find the bound value because I assign the value dynamically.
Code:
<asp:TemplateField HeaderText="Favorite Food" SortExpression="Food">
    <EditItemTemplate>
        <asp:DropDownList ID="FoodDropDownList" runat="server">
            <asp:ListItem Text="[ Select ]" Value="" />
        </asp:DropDownList>
    </EditItemTemplate>
    <ItemTemplate><%# Eval("Food") %></ItemTemplate>
</asp:TemplateField>

private readonly string[] food = new string[] { "Apple", "Bananna", "Orange", "Mango", "Avacado" };

private void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowIndex != -1 && e.Row.RowState == DataControlRowState.Edit)
    {
        Person p = (Person)e.Row.DataItem;

        DropDownList ddl = (DropDownList)e.Row.FindControl("FoodDropDownList");
        foreach (string food in this.food)
        {
            ddl.Items.Add(new ListItem(food, food));
        }
        ddl.SelectedIndex = ddl.Items.IndexOf(new ListItem(p.Food, p.Food));
    }
}

this throws an exception because it's trying to assign the selected value before the list of options is loaded
Code:
<asp:TemplateField HeaderText="Favorite Food" SortExpression="Food">
    <EditItemTemplate>
        <asp:DropDownList ID="FoodDropDownList" runat="server" SelectedValue='<%#Bind("Food") %>'>
            <asp:ListItem Text="[ Select ]" Value="" />
        </asp:DropDownList>
    </EditItemTemplate>
    <ItemTemplate><%# Eval("Food") %></ItemTemplate>
</asp:TemplateField>

private readonly string[] food = new string[] { "Apple", "Bananna", "Orange", "Mango", "Avacado" };

private void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowIndex != -1 && e.Row.RowState == DataControlRowState.Edit)
    {
        DropDownList ddl = (DropDownList)e.Row.FindControl("FoodDropDownList");
        foreach (string food in this.food)
        {
            ddl.Items.Add(new ListItem(food, food));
        }
    }
}

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top