Question

GridView Update using ObjectDataSource

Asked by: MadhuMenong

Dear Friends,

I am using ASP.Net / GridView to list a number of cities.
Step one is to select the Country from a dropdownlist which is set to

AutoPostBack=true.

The GridView is being populated using an ObjectDataSource  and

ObjectDataTypeName details of which are given in the code.

Entity : CityEntity
DAO : CityDAO

The Issue:

In the edit mode the country is changed to a dropdownlist. I change the selected country and click the update button/link to save the changes.

But when the city table is updated the CountryName fields is left blank. The city table records both the CountryId and Country name so I need to pass both the Text and value of the DropDownList.

I tried to handle the onupdating event and changing the

e.InputParameters["objcity"] to include the country name in the CityEntity, but

getting the error InputParameters is a readonly field.

Is there a way in which:
1. With minimal change in code and without handling the OnUpdating event I can

pass the CountryName from the ddlCountry control. I need to pass both the

CountryID i.e ddlCountry.SelectedValue and the CountryName i.e

ddlCountry.SelectedItem.Text to be passed for update.

2. e.InputParameters is showing as readonly. But the microsoft portal

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.objectdatasour

ceview.updating(VS.80).aspx the sample is adding Key / Value to the

e.InputParameters. Now how is it possible.
Am I missing something.

Please help.

All related code and table structure is given in the code.

Thank You
Madhu Menon

Entity
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace GridView.City
{
    public class CityEntity
    {
        public enum city : int
        {
            AutoID = 0,
            Status = 1,
            CityID = 2,
            CityName = 3,
            CountryName = 4,
            CountryID = 5,
            TimeZone = 6,
            ModifiedBy = 7,
            ModifiedDate = 8
 
        }
        #region  Private Variable
 
        private int _AutoID = 0;
 
        private int _Status = 0;
 
        private int _CityID = 0;
 
        private string _CityName = "";
 
        private string _CountryName = "";
 
        private int _CountryID = 0;
 
        private string _TimeZone = "";
 
        private int _ModifiedBy = 0;
 
 
        private DateTime _ModifiedDate = System.DateTime.Now;
 
        #endregion Private Variable
 
 
        public int AutoID
        {
            get { return _AutoID; }
            set { _AutoID = value; }
        }
 
        public int Status
        {
            get { return _Status; }
            set { _Status = value; }
        }
 
 
        public int CityID
        {
            get { return _CityID; }
            set { _CityID = value; }
        }
 
        public string CityName
        {
            get { return _CityName; }
            set { _CityName = value; }
        }
 
        public string CountryName
        {
            get { return _CountryName; }
            set { _CountryName = value; }
        }
 
 
        public int CountryID
        {
            get { return _CountryID; }
            set { _CountryID = value; }
        }
 
 
 
 
        public string TimeZone
        {
            get { return _TimeZone; }
            set { _TimeZone = value; }
        }
 
 
        public int ModifiedBy
        {
            get { return _ModifiedBy; }
            set { _ModifiedBy = value; }
        }
 
 
        public System.DateTime ModifiedDate
        {
            get
            {
                return _ModifiedDate;
 
            }
            set
            {
                _ModifiedDate = value;
            }
        }
    }
}
 
 
_____________________________________________________
 
DAO
 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
 
 
namespace GridView.City
{
    public class CityDAO
    {
        private int i = 0;
        private string feedbackMsg = string.Empty;
        private string connString = 
 
WebConfigurationManager.ConnectionStrings["PegasusConnectionString2"].ToString()
 
;
        Parameter ObjPara = new Parameter();
        CommonClass ObjCom = new CommonClass();
        SqlConnection con;
        SqlCommand cmd;
        DataTable dt;
        private DataSet ds;
        private SqlDataAdapter da;
 
        public string Add(CityEntity objcity)
        {
            try
            {
                con = new SqlConnection(connString);
                con.Open();
                cmd = new SqlCommand(SysConstants.SP_CityCreate, con);
                cmd.CommandType = CommandType.StoredProcedure;
                //cmd.Parameters.Add(cAutoID, SqlDbType.Int).Value = 
 
objchain.AutoID;  
                cmd.Parameters.Add(ObjPara.GetParam(SysConstants.CityIDAt, 
 
ObjCom.GetId(SysConstants.CityID), ParameterDirection.Input));
                cmd.Parameters.Add(ObjPara.GetParam(SysConstants.CityNameAt, 
 
objcity.CityName, ParameterDirection.Input));
                cmd.Parameters.Add(ObjPara.GetParam("@CountryName", 
 
objcity.CountryName, ParameterDirection.Input));
                cmd.Parameters.Add(ObjPara.GetParam("@CountryID", 
 
objcity.CountryID, ParameterDirection.Input));
                cmd.Parameters.Add(ObjPara.GetParam(SysConstants.TimeZoneAt, 
 
objcity.TimeZone, ParameterDirection.Input));
                cmd.Parameters.Add(ObjPara.GetParam("@ModifiedBy", 
 
objcity.ModifiedBy, ParameterDirection.Input));
 
 
 
                i = cmd.ExecuteNonQuery();
 
 
                if (i == -1)
                {
                    feedbackMsg = 
 
WebConfigurationManager.AppSettings["Add"].ToString();
                    return feedbackMsg;
                }
                else
                {
                    feedbackMsg = 
 
WebConfigurationManager.AppSettings["add_failure"].ToString();
                    return feedbackMsg;
                }
 
            }
            catch (Exception e)
            {
                feedbackMsg = 
 
WebConfigurationManager.AppSettings["add_failure"].ToString() + 
 
e.Message.ToString();
                return feedbackMsg;
            }
            finally
            {
                cmd.Dispose();
                con.Close();
                con.Dispose();
            }
        }
 
        public string Update(CityEntity objcity)
        {
            try
            {
                con = new SqlConnection(connString);
                con.Open();
                cmd = new SqlCommand("SP_CityUpdate", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(ObjPara.GetParam("@AutoID", objcity.AutoID, 
 
ParameterDirection.Input));
                cmd.Parameters.Add(ObjPara.GetParam("@CityID", objcity.CityID, 
 
ParameterDirection.Input));
                cmd.Parameters.Add(ObjPara.GetParam("@CityName", 
 
objcity.CityName, ParameterDirection.Input));
                cmd.Parameters.Add(ObjPara.GetParam("@CountryName", 
 
objcity.CountryName, ParameterDirection.Input));
                cmd.Parameters.Add(ObjPara.GetParam("@CountryID", 
 
objcity.CountryID, ParameterDirection.Input));
                cmd.Parameters.Add(ObjPara.GetParam("@TimeZone", 
 
objcity.TimeZone, ParameterDirection.Input));
                cmd.Parameters.Add(ObjPara.GetParam("@ModifiedBy", 
 
objcity.ModifiedBy, ParameterDirection.Input));
 
                i = cmd.ExecuteNonQuery();
 
 
                if (i == -1)
                {
                    feedbackMsg = "Successfully Updated!!!";
                    return feedbackMsg;
                }
                else
                {
                    feedbackMsg = "Update Failed!!!";
                    return feedbackMsg;
                }
 
            }
            catch (Exception e)
            {
                feedbackMsg = "Update Failed";
                return feedbackMsg;
            }
            finally
            {
                cmd.Dispose();
                con.Close();
                con.Dispose();
            }
        }
        public string Delete(int CityID)
        {
            try
            {
                con = new SqlConnection(connString);
                con.Open();
                cmd = new SqlCommand("SP_CityDelete", con);
                cmd.CommandType = CommandType.StoredProcedure;
 
                cmd.Parameters.Add(ObjPara.GetParam("@CityID", CityID, 
 
ParameterDirection.Input));
 
                i = cmd.ExecuteNonQuery(); //Working but getting correct values
                if (i == -1)
                {
                    feedbackMsg = 
 
WebConfigurationManager.AppSettings["Delete"].ToString();
                    return feedbackMsg;
                }
                else
                {
                    feedbackMsg = 
 
WebConfigurationManager.AppSettings["Delete_failure"].ToString();
                    return feedbackMsg;
                }
 
            }
            catch (Exception e)
            {
                feedbackMsg = 
 
WebConfigurationManager.AppSettings["delete_failure"].ToString() + 
 
e.Message.ToString();
                return feedbackMsg;
            }
            finally
            {
                cmd.Dispose();
                con.Close();
                con.Dispose();
            }
        }
 
        public CityEntity getData(int CityID)
        {
            CityEntity city = new CityEntity();
 
            try
            {
                SqlDataReader dr;
                con = new SqlConnection(connString);
                con.Open();
                cmd = new SqlCommand("SP_CityGetData", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(ObjPara.GetParam("@CityID", CityID, 
 
ParameterDirection.Input));
 
                dr = cmd.ExecuteReader();
 
                if (dr != null)
                {
                    while (dr.Read())
                    {
                        if (dr.HasRows)
                        {
                            city.AutoID = (int)dr["AutoID"];
                            city.CityID = (int)dr["CityID"];
                            city.CityName = dr["CityName"].ToString();
                            city.CountryID = (int)dr["CountryID"];
                            city.CountryName = dr["CountryName"].ToString();
                            city.TimeZone = dr["TimeZone"].ToString();
                            city.ModifiedBy = (int)dr["ModifiedBy"];
                        }
                    }
 
                    dr.Dispose();
                }
                return city;
 
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message);
            }
            finally
            {
                cmd.Dispose();
                con.Close();
                con.Dispose();
            }
        }
 
        public List<CityEntity> GetList()
        {
 
            try
            {
                SqlDataReader dr;
                List<CityEntity> ListCity = new List<CityEntity>();
                con = new SqlConnection(connString);
                cmd = new SqlCommand("SP_CityGetAllData", con);
                cmd.CommandType = CommandType.StoredProcedure;
                con.Open();
                dr = cmd.ExecuteReader();
                while (dr.Read())
                {
 
                    if (dr.HasRows)
                    {
                        CityEntity city = new CityEntity();
                        city.AutoID = (int)dr["AutoID"];
                        city.CityID = (int)dr["CityID"];
                        city.CityName = dr["CityName"].ToString();
                        city.CountryID = (int)dr["CountryID"];
                        city.TimeZone = dr["TimeZone"].ToString();
                        city.ModifiedBy = (int)dr["ModifiedBy"];
                        ListCity.Add(city);
                    }
 
 
                }
                return ListCity;
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message);
            }
            finally
            {
                con.Close();
                cmd.Dispose();
                con.Dispose();
            }
 
        }
 
        public Hashtable SearchData(String Searchwhat)
        {
 
            try
            {
                Hashtable ht = new Hashtable();
                SqlDataReader dr;
                con = new SqlConnection(connString);
                con.Open();
                cmd = new SqlCommand("SP_CitySearchData", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(ObjPara.GetParam("@SearchOn", Searchwhat, 
 
ParameterDirection.Input));
 
 
                dr = cmd.ExecuteReader();
 
                if (dr != null)
                {
                    while (dr.Read())
                    {
                        if (dr.HasRows)
                        {
 
                            ht.Add(dr["CityName"], dr["CityID"]);
                        }
 
                    }
 
                    dr.Dispose();
                }
                return ht;
            }
            catch (Exception ex)
            {
 
 
                throw new ArgumentException(ex.Message);
            }
            finally
            {
                cmd.Dispose();
                con.Close();
                con.Dispose();
            }
        }
 
 
        public DataTable GridSearch(string strcity, string strcountry, int 
 
pagesize, int currentpage)
        {
            try
            {
                con = new SqlConnection(connString);
                con.Open();
                dt = new DataTable();
                cmd = new SqlCommand("SP_CityLookup", con);
                cmd.CommandType = CommandType.StoredProcedure;
 
                cmd.Parameters.Add("@city_prefix", SqlDbType.VarChar);
                cmd.Parameters[0].Value = strcity;
 
                cmd.Parameters.Add("@country_prefix", SqlDbType.VarChar);
                cmd.Parameters[1].Value = strcountry;
 
                cmd.Parameters.Add("@PageSize", SqlDbType.Int);
                cmd.Parameters[2].Value = pagesize;
 
                cmd.Parameters.Add("@CurrentPage", SqlDbType.Int);
                cmd.Parameters[3].Value = currentpage;
 
                SqlParameter parm = new SqlParameter();
 
                parm = cmd.Parameters.Add("@PageCount", SqlDbType.Int);
                parm.Direction = ParameterDirection.Output;
 
                da = new SqlDataAdapter();
                da.SelectCommand = cmd;
                da.Fill(dt);
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message);
            }
            finally
            {
                cmd.Dispose();
                con.Close();
                con.Dispose();
            }
            return dt;
        }
 
        public DataTable GridSearchLookup(string strcity, int pagesize, int 
 
currentpage, int countryID, string countryName, ref int TotalRows)
        {
            try
            {
                con = new SqlConnection(connString);
 
                dt = new DataTable();
                cmd = new SqlCommand("SP_CityLookupByCountry", con);
                cmd.CommandType = CommandType.StoredProcedure;
 
                cmd.Parameters.Add("@Prefix", SqlDbType.VarChar);
                cmd.Parameters[0].Value = strcity;
 
 
                cmd.Parameters.Add("@PageSize", SqlDbType.Int);
                cmd.Parameters[1].Value = pagesize;
 
                cmd.Parameters.Add("@CurrentPage", SqlDbType.Int);
                cmd.Parameters[2].Value = currentpage;
 
                cmd.Parameters.Add("@CountryID", SqlDbType.Int);
                cmd.Parameters[3].Value = countryID;
                cmd.Parameters.Add("@CountryName", SqlDbType.VarChar);
                cmd.Parameters[4].Value = countryName;
 
                SqlParameter parm = new SqlParameter();
 
                parm = cmd.Parameters.Add("@PageCount", SqlDbType.Int);
                parm.Direction = ParameterDirection.Output;
 
                con.Open();
 
                da = new SqlDataAdapter();
                da.SelectCommand = cmd;
                da.Fill(dt);
 
                TotalRows = (int)cmd.Parameters["@PageCount"].Value;
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message);
            }
            finally
            {
                cmd.Dispose();
                con.Close();
                con.Dispose();
            }
            return dt;
        }
 
 
 
 
        public DataSet FetchByCityID(int CityID)
        {
            try
            {
                con = new SqlConnection(connString);
                con.Open();
                ds = new DataSet();
 
                cmd = new SqlCommand("SP_CityGetData", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(ObjPara.GetParam("@CityID", CityID, 
 
ParameterDirection.Input));
 
                da = new SqlDataAdapter(cmd);
                da.Fill(ds);
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message);
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
            return ds;
        }
 
 
        //to fill the country dropdown in city form
        public DataSet FillCountryList()
        {
            try
            {
                con = new SqlConnection(connString);
                con.Open();
                ds = new DataSet();
                da = new SqlDataAdapter("SP_CountryDisplay", con);
                da.Fill(ds, "Country");
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message);
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
            return ds;
        }
 
        //end by dipti of cityform
 
        //fill city dropdownlist--dipti
        public DataSet FillCityList()
        {
            try
            {
                con = new SqlConnection(connString);
                con.Open();
                ds = new DataSet();
                da = new SqlDataAdapter("SP_CityDisplay", con);
                da.Fill(ds, "City");
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message);
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
            return ds;
        }
 
        //amit work
        public DataSet GetCitiesByCountrySP(int countryID)
        {
            try
            {
                con = new SqlConnection(connString);
                con.Open();
                ds = new DataSet();
                SqlCommand cmd = new 
 
SqlCommand(SysConstants.SP_CitySelectedIndexDisplay, con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(ObjPara.GetParam(SysConstants.CountryIDAt, 
 
countryID, ParameterDirection.Input));
                SqlDataAdapter da = new SqlDataAdapter(cmd);
 
                da.Fill(ds, "City");
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message);
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
            return ds;
        }
 
        public DataSet GetCitiesByCountry(int countryID)
        {
            try
            {
                con = new SqlConnection(connString);
                con.Open();
                ds = new DataSet();
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "Select [AutoID],	
 
[CityID],[CityName],[CountryID],[CountryName],[TimeZone],[ModifiedBy],[ModifiedD
 
ate] from tblCity Where CountryID = " + countryID.ToString() + " Order by 
 
CityName";
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
          
                SqlDataAdapter da = new SqlDataAdapter(cmd);
 
                da.Fill(ds, "City");
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message);
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
            return ds;
        }
        //end amit
        //narendar work
 
        public DataTable GridSearch(string strcity, int pagesize, int 
 
currentpage, ref int TotalRows)
        {
            try
            {
                con = new SqlConnection(connString);
 
                dt = new DataTable();
                cmd = new SqlCommand("SP_CityLookup", con);
                cmd.CommandType = CommandType.StoredProcedure;
 
                cmd.Parameters.Add("@Prefix", SqlDbType.VarChar);
                cmd.Parameters[0].Value = strcity;
 
 
                cmd.Parameters.Add("@PageSize", SqlDbType.Int);
                cmd.Parameters[1].Value = pagesize;
 
                cmd.Parameters.Add("@CurrentPage", SqlDbType.Int);
                cmd.Parameters[2].Value = currentpage;
 
                SqlParameter parm = new SqlParameter();
 
                parm = cmd.Parameters.Add("@PageCount", SqlDbType.Int);
                parm.Direction = ParameterDirection.Output;
 
                con.Open();
 
                da = new SqlDataAdapter();
                da.SelectCommand = cmd;
                da.Fill(dt);
 
                TotalRows = (int)cmd.Parameters["@PageCount"].Value;
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message);
            }
            finally
            {
                cmd.Dispose();
                con.Close();
                con.Dispose();
            }
            return dt;
        }
 
        public DataTable Fetch()
        {
            try
            {
                con = new SqlConnection(connString);
                con.Open();
                dt = new DataTable();
                da = new SqlDataAdapter(SysConstants.SP_CityGetAllData, con);
                da.Fill(dt);
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message);
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
            return dt;
        }
 
 
    }
}
 
___________________________________________________________
 
ASPX
 
<%@ Page Language="C#" AutoEventWireup="true" 
 
CodeBehind="GridView_InsertUpdateDelete.aspx.cs" 
 
Inherits="MadhuASPTutorial.ObjectDataSourceGridView.GridView_InsertUpdateDelete" 
 
%>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:ObjectDataSource ID="odsCountry" runat="server" 
            TypeName="GridView.City.CityDAO" 
 
SelectMethod="FillCountryList"></asp:ObjectDataSource>
            
    <asp:DropDownList ID="ddlCountry" runat="server" DataSourceID="odsCountry" 
    DataTextField="CountryName" DataValueField="CountryID" 
 
AutoPostBack="true"></asp:DropDownList>
    
    <br />
    <br />
    
    <asp:ObjectDataSource ID="odsCity" runat="server" 
 
TypeName="GridView.City.CityDAO" 
            DataObjectTypeName="GridView.City.CityEntity" DeleteMethod="Delete" 
            InsertMethod="Add" SelectMethod="GetCitiesByCountry" 
 
UpdateMethod="Update" 
            onupdating="odsCity_Updating" 
            OldValuesParameterFormatString="original_{0}">
        <DeleteParameters>
            <asp:Parameter Name="CityID" Type="Int32" />
        </DeleteParameters>
        <SelectParameters>
            <asp:ControlParameter ControlID="ddlCountry" DefaultValue="0" 
 
Name="countryID" 
                PropertyName="SelectedValue" Type="Int32" />
        </SelectParameters>
     </asp:ObjectDataSource>
    
    <asp:GridView ID="gvCities" runat="server" DataSourceID="odsCity" 
            DataKeyNames="CityID" AllowPaging="True"
     AutoGenerateColumns="False">
     <Columns>
         <asp:CommandField ShowEditButton="true" />
         <asp:TemplateField HeaderText="AutoID">
         <ItemTemplate> <asp:Label ID="lblAutoID" runat="server" Text='<%# 
 
Eval("AutoID") %>' ></asp:Label></ItemTemplate>
          <EditItemTemplate><asp:Label ID="lblAutoIDE" runat="server" Text='<%# 
 
Bind("AutoID") %>' ></asp:Label></EditItemTemplate>
         </asp:TemplateField>
         <asp:TemplateField HeaderText="CityID">
         <ItemTemplate> <asp:Label ID="lblCityID" runat="server" Text='<%# 
 
Eval("CityID") %>' ></asp:Label></ItemTemplate>
         <EditItemTemplate> <asp:Label ID="lblCityIDE" runat="server" Text='<%# 
 
Bind("CityID") %>' ></asp:Label></EditItemTemplate>
         </asp:TemplateField>
         <asp:TemplateField HeaderText="CityName">
         <ItemTemplate> <asp:Label ID="lblCityName" runat="server" Text='<%# 
 
Eval("CityName") %>' ></asp:Label></ItemTemplate>
         <EditItemTemplate> <asp:TextBox ID="txtCityName" runat="server" 
 
Text='<%# Bind("CityName") %>' ></asp:TextBox>
         <asp:RequiredFieldValidator ID="rfvCityName" runat="server" 
 
ControlToValidate="txtCityName" ErrorMessage="City Name is Required!!!" 
 
Display="Static">*</asp:RequiredFieldValidator>
         </EditItemTemplate>
         </asp:TemplateField>
         
         <asp:TemplateField HeaderText="CountryName">
         <ItemTemplate> <asp:Label ID="lblCountryName" runat="server" Text='<%# 
 
Eval("CountryName") %>' ></asp:Label></ItemTemplate>
         
         <EditItemTemplate> <asp:DropDownList ID="ddlCountry" runat="server" 
 
DataSourceID="odsCountry1" DataTextField="CountryName" 
 
DataValueField="CountryID" SelectedValue='<%# Bind("CountryID") %>' >
                <asp:ListItem Value="-1" Text="Select"></asp:ListItem>
         </asp:DropDownList>
         <asp:RequiredFieldValidator ID="rfvCountry" runat="server" 
 
ControlToValidate="ddlCountry" InitialValue="-1" ErrorMessage="Country should be 
 
selelcted!!!" Display="Static">*</asp:RequiredFieldValidator>
         <asp:ObjectDataSource ID="odsCountry1" runat="server" 
 
TypeName="GridView.City.CityDAO" 
 
SelectMethod="FillCountryList"></asp:ObjectDataSource>
         </EditItemTemplate>
         </asp:TemplateField>
         <asp:TemplateField HeaderText="TimeZone">
         <ItemTemplate> <asp:Label ID="lblTimeZone" runat="server" Text='<%# 
 
Eval("TimeZone") %>' ></asp:Label></ItemTemplate>
         <EditItemTemplate> <asp:TextBox ID="txtTimeZone" runat="server" 
 
Text='<%# Bind("TimeZone") %>' ></asp:TextBox></EditItemTemplate>
         </asp:TemplateField>
         <asp:TemplateField HeaderText="Modified By">
         <ItemTemplate> <asp:Label ID="lblModifiedBy" runat="server" Text='<%# 
 
Eval("ModifiedBy") %>' ></asp:Label></ItemTemplate>
         <EditItemTemplate> <asp:TextBox ID="txtAModifiedBy" runat="server" 
 
Text='<%# Bind("ModifiedBy") %>'></asp:TextBox></EditItemTemplate>
         </asp:TemplateField>
         <asp:TemplateField HeaderText="Modified Date">
         <ItemTemplate> <asp:Label ID="lblModifiedDate" runat="server" Text='<%# 
 
Eval("ModifiedDate") %>' ></asp:Label></ItemTemplate>
         <EditItemTemplate> <asp:TextBox ID="txtModifiedDate" runat="server" 
 
Text='<%# Bind("ModifiedDate") %>' ></asp:TextBox></EditItemTemplate>
         </asp:TemplateField>
                  
     </Columns>
     
     
     </asp:GridView>
    
    </div>
    </form>
</body>
</html>
 
 
_________________________________________________________
 
ASPX.cs
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace MadhuASPTutorial.ObjectDataSourceGridView
{
    public partial class GridView_InsertUpdateDelete : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
 
        }
 
        protected void odsCity_Updating(object sender, 
 
ObjectDataSourceMethodEventArgs e)
        {
            GridView.City.CityEntity city = new GridView.City.CityEntity();
 
            // The names of the parameters are the same as
            // the variable names for the method that is invoked to
            // perform the Update. The InputParameters collection is
            // an IDictionary collection of name/value pairs,
            // not a ParameterCollection.
 
            city = (GridView.City.CityEntity)e.InputParameters["objcity"];
 
            city.CountryName = ddlCountry.SelectedItem.Text;
            //e.InputParameters.Remove("objcity");
       
           // e.InputParameters.Add("objcity", city);
           
            city = null;
 
           
           
        }
    }
}
 
_________________________________________________
 
Table Structure
 
CREATE TABLE [dbo].[tblCountry](
	[AutoID] [int] IDENTITY(1,1) NOT NULL,
	[CountryID] [int] NOT NULL,
	[CountryName] [varchar](100) NOT NULL,
	[CountryCode] [varchar](2) NULL,
	[RegionName] [varchar](100) NULL,
	[RegionID] [int] NULL,
	[ISD] [nchar](10) NULL,
	[CurrencyCode] [varchar](10) NULL,
	[CurrencyName] [nvarchar](100) NULL,
	[TimeZone] [nchar](100) NULL,
	[ModifiedBy] [int] NOT NULL,
	[ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]
 
 
CREATE TABLE [dbo].[tblCity](
	[AutoID] [int] IDENTITY(1,1) NOT NULL,
	[CityID] [int] NULL,
	[CityName] [nvarchar](100) NULL,
	[CountryID] [int] NULL,
	[CountryName] [nvarchar](100) NULL,
	[TimeZone] [nchar](10) NULL,
	[ModifiedBy] [int] NULL,
	[ModifiedDate] [datetime] NULL
) ON [PRIMARY]
 
 
_________________________________
 
Sample data
 
Country
 
11,110,Afghanistan,,Asia,12,93        ,AFN,Afghanistan Afghanis,                 
 
                                                                                 
 
  ,0,2009-06-28 03:13:37.500000000
12,111,Albania,,Europe,5,355       ,ALL,Albania Leke,                            
 
                                                                        
 
,0,2009-06-28 03:17:27.577000000
 
 
City
 
 
8222,8291,Mazar-I-Sharif,110,Afghanistan,          ,100,2009-03-17 
 
20:50:29.080000000
8224,8293,Herat,111,Afghanistan,          ,100,2009-08-20 01:06:52.700000000
8226,8295,Kabul,110,Afghanistan,          ,100,2009-03-17 20:50:29.080000000
8228,8297,Kandahar,110,Afghanistan,          ,100,2009-03-17 20:50:29.080000000
8230,8299,Tirana,111,Albania,          ,100,2009-03-17 20:50:29.080000000

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
308:
309:
310:
311:
312:
313:
314:
315:
316:
317:
318:
319:
320:
321:
322:
323:
324:
325:
326:
327:
328:
329:
330:
331:
332:
333:
334:
335:
336:
337:
338:
339:
340:
341:
342:
343:
344:
345:
346:
347:
348:
349:
350:
351:
352:
353:
354:
355:
356:
357:
358:
359:
360:
361:
362:
363:
364:
365:
366:
367:
368:
369:
370:
371:
372:
373:
374:
375:
376:
377:
378:
379:
380:
381:
382:
383:
384:
385:
386:
387:
388:
389:
390:
391:
392:
393:
394:
395:
396:
397:
398:
399:
400:
401:
402:
403:
404:
405:
406:
407:
408:
409:
410:
411:
412:
413:
414:
415:
416:
417:
418:
419:
420:
421:
422:
423:
424:
425:
426:
427:
428:
429:
430:
431:
432:
433:
434:
435:
436:
437:
438:
439:
440:
441:
442:
443:
444:
445:
446:
447:
448:
449:
450:
451:
452:
453:
454:
455:
456:
457:
458:
459:
460:
461:
462:
463:
464:
465:
466:
467:
468:
469:
470:
471:
472:
473:
474:
475:
476:
477:
478:
479:
480:
481:
482:
483:
484:
485:
486:
487:
488:
489:
490:
491:
492:
493:
494:
495:
496:
497:
498:
499:
500:
501:
502:
503:
504:
505:
506:
507:
508:
509:
510:
511:
512:
513:
514:
515:
516:
517:
518:
519:
520:
521:
522:
523:
524:
525:
526:
527:
528:
529:
530:
531:
532:
533:
534:
535:
536:
537:
538:
539:
540:
541:
542:
543:
544:
545:
546:
547:
548:
549:
550:
551:
552:
553:
554:
555:
556:
557:
558:
559:
560:
561:
562:
563:
564:
565:
566:
567:
568:
569:
570:
571:
572:
573:
574:
575:
576:
577:
578:
579:
580:
581:
582:
583:
584:
585:
586:
587:
588:
589:
590:
591:
592:
593:
594:
595:
596:
597:
598:
599:
600:
601:
602:
603:
604:
605:
606:
607:
608:
609:
610:
611:
612:
613:
614:
615:
616:
617:
618:
619:
620:
621:
622:
623:
624:
625:
626:
627:
628:
629:
630:
631:
632:
633:
634:
635:
636:
637:
638:
639:
640:
641:
642:
643:
644:
645:
646:
647:
648:
649:
650:
651:
652:
653:
654:
655:
656:
657:
658:
659:
660:
661:
662:
663:
664:
665:
666:
667:
668:
669:
670:
671:
672:
673:
674:
675:
676:
677:
678:
679:
680:
681:
682:
683:
684:
685:
686:
687:
688:
689:
690:
691:
692:
693:
694:
695:
696:
697:
698:
699:
700:
701:
702:
703:
704:
705:
706:
707:
708:
709:
710:
711:
712:
713:
714:
715:
716:
717:
718:
719:
720:
721:
722:
723:
724:
725:
726:
727:
728:
729:
730:
731:
732:
733:
734:
735:
736:
737:
738:
739:
740:
741:
742:
743:
744:
745:
746:
747:
748:
749:
750:
751:
752:
753:
754:
755:
756:
757:
758:
759:
760:
761:
762:
763:
764:
765:
766:
767:
768:
769:
770:
771:
772:
773:
774:
775:
776:
777:
778:
779:
780:
781:
782:
783:
784:
785:
786:
787:
788:
789:
790:
791:
792:
793:
794:
795:
796:
797:
798:
799:
800:
801:
802:
803:
804:
805:
806:
807:
808:
809:
810:
811:
812:
813:
814:
815:
816:
817:
818:
819:
820:
821:
822:
823:
824:
825:
826:
827:
828:
829:
830:
831:
832:
833:
834:
835:
836:
837:
838:
839:
840:
841:
842:
843:
844:
845:
846:
847:
848:
849:
850:
851:
852:
853:
854:
855:
856:
857:
858:
859:
860:
861:
862:
863:
864:
865:
866:
867:
868:
869:
870:
871:
872:
873:
874:
875:
876:
877:
878:
879:
880:
881:
882:
883:
884:
885:
886:
887:
888:
889:
890:
891:
892:
893:
894:
895:
896:
897:
898:
899:
900:
901:
902:
903:
904:
905:
906:
907:
908:
909:
910:
911:
912:
913:
914:
915:
916:
917:
918:
919:
920:
921:
922:
923:
924:
925:
926:
927:
928:
929:
930:
931:
932:
933:
934:
935:
936:
937:
938:
939:
940:
941:
942:
943:
944:
945:
946:
947:
948:
949:
950:
951:
952:
953:
954:
955:
956:
957:
958:
959:
960:
961:
962:
963:
964:
965:
966:
967:
968:
969:
970:
971:
972:
973:
974:
975:
976:
977:
978:
979:
980:
981:
982:
983:
984:
985:
986:
987:
988:
989:
990:
991:
992:
993:
994:
995:
996:
997:
998:
999:
1000:
1001:
1002:
1003:
1004:
1005:
1006:
1007:
1008:
1009:
1010:
1011:
1012:
1013:
1014:
1015:
1016:
1017:
1018:
1019:
1020:
1021:
1022:
1023:
1024:
1025:
1026:
1027:
1028:
1029:
1030:
1031:
1032:
1033:
1034:
1035:
1036:
1037:
1038:
1039:
1040:
1041:
1042:
1043:
1044:
1045:
1046:
1047:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-08-28 at 04:38:29ID24689438
Tags

ASP.Net GridView

Topics

.NET Framework 3.x versions

,

.NET Framework 2.x

,

Programming for ASP.NET

Participating Experts
1
Points
500
Comments
10

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Country and a City.
    ok i am using this code to get the country whenever the user is going to come to my site. The problem is i also have to get the name of the City in that Country. Is this possible ? Here is what i have so far. If anyone can help me out i would appriciate it. Thanks. import ja...
  2. Country Region City Database
    Hi there, I'm developing an application that requires the user to select their country region city. Users will then be able to search for other memebers based on their country region city. My question is where can i get the best database that contains all the countries with...
  3. Country, Region, City Database
    ASP.NET C# Hi there, I'm looking to implement a Country, Region, City database on my site. I've found an excellent free one at (http://www.maxmind.com/app/geolitecity) . It's really detailed and exactly what i'm after. It is supplied in csv and binary format. I'd like to ...
  4. list of countries/cities table
    Any one have a sql server tables contains all world countries, and cities? Please tell me where Thanks,

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: KPMT-TechnicianPosted on 2009-08-29 at 17:29:37ID: 25215930

Interesting problem, could you run a backup of your data source and post it so I can recreate the environment.  Will help in troubleshooting this issue.

Robert Fidler
Springfield, Missouri

 

by: MadhuMenongPosted on 2009-08-31 at 04:30:34ID: 25221946

Hi KPMT-Technician,

Sorry but didnt understand what you mean by "could you run a backup of your data source and post it". Do you want me to send you the table structure and all the data. Is that what you are asking for.

Please clarify. Thanks

 

by: KPMT-TechnicianPosted on 2009-08-31 at 06:20:14ID: 25222512

Would like to recreate a testing enviornment to help troubleshoot this issue.  I will need a copy of the data base (only a portion of the database that the above code uses and sample data).

 

by: MadhuMenongPosted on 2009-09-01 at 05:27:34ID: 25230810

Hi KPMT-Technician,
Please find attached the CountryCity.xls data file and the countryCitySP.txt file for stored procedures.

Thanks for your efforts.

 

by: KPMT-TechnicianPosted on 2009-09-01 at 05:55:59ID: 25231032

I will have free time this later this evening to help.  I will post as soon as I know more.

 

by: KPMT-TechnicianPosted on 2009-09-01 at 22:58:31ID: 25238271

Everything went in well but I am missing the SysConstants class and the CommonClass class.  I started modifing the classes but it would be much quicker if you'd add the needed classes.

 

by: MadhuMenongPosted on 2009-09-02 at 23:00:09ID: 25248165

Hi

Sorry missed out the constants. I have attached the SysConstants.txt file where in you will find all the required constants. In case some constants are missing then the same can by created by you.

If the constant name is CityID then

public const string CityID = "CityID";

If the Constant name is CityIDAt, here the 'At' as suffix indicate a parameter then

public const string CityIDAt = "@CityID";

Notice the difference in value of the CityID and CityIDAt. This is standard across.

Thank you very much for your time and effort.




 

by: MadhuMenongPosted on 2009-09-02 at 23:17:25ID: 25248212

Hi Sorry,

Missed the Common class. Its nothing but a random number generator to create unique number. Code is attached.

 

by: KPMT-TechnicianPosted on 2009-09-11 at 19:29:12ID: 25314809

I have gotten a working sample to gether but I am unable to recreate your error.  I may have changed something without realizing it.  I make a couple adjustments to help troubleshoot and when I run the code it works for me.  I added:
     Default values to the [SP_CityUpdate]  stored proc.
     MessageBox to display error messages.  
     Altered the object datasource updating event.
     Added an object datasource updated event.

I have attached a zip file of my project so you can setup and run while comparing code to see the differences.

Robert Fidler
Springfield, Mo

**Attached project was created with the above code then condenced to make a sample project.  On a Windows 2008 x64 system using Visual Studio 2008 Pro. and SQL Server 2008.  Uncompress project and rename all files by removing the .txt file extension.  Us the database backup located in the AppData folder to recreate data source.  Update the web.config file with the correct connection string to connect to your newly created data source.**

 

by: MadhuMenongPosted on 2009-09-20 at 06:29:16ID: 31631135

Hi KPMT-Technician, Sorry to respond so late. Yes the solution you gave is an excellent way without visiting the database to fetch the CountryName the way I solved the problem. But yours is a better solution. Also I got to learn the e.InputParameters funda of .Net.

Thanks a lot.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...