Editable Gridview with code behind data source from ODBC - asp.net

I am trying to make a small gridview that lists the results of a query against a non standard SQL db, and with this information I want the user to be able to edit a column or two to update the data in the db. I know this is easy with an sqldatasource control but I lack that luxury and I am having trouble switching from my itemTemplates in the gridview to the edittemplates when I fire the gridview's edit event.
any pointers?
some code:
<asp:GridView ID="ExamEditGridView" runat="server" OnRowEditing="EditExam" OnRowUpdating="SaveEdit"
DataKeyNames="iproc_code" AllowSorting="true" AutoGenerateColumns="false" AutoGenerateEditButton="true">
<HeaderStyle BackColor="#006633" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<Columns>
<asp:TemplateField HeaderText="Exam Title">
<ItemTemplate>
<asp:Label ID="col1" runat="server" Text='<%# Bind("rpt_descrip") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="EditText" runat="server" Text='<%# Bind("rpt_descrip") %>' Visible="false" />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Short Description" DataField="short_descrip" />
<asp:BoundField HeaderText="Description" DataField="descrip" />
<asp:BoundField HeaderText="Sched Note" DataField="sched_note" />
</Columns>
</asp:GridView>
code behind:
(the query is just a simlpe select statement)
string mod_id = modSelect.SelectedValue;
string query = qry + mod_id;
using (OdbcConnection connection = new OdbcConnection(DbConnectionString))
{
OdbcDataAdapter adapter = new OdbcDataAdapter(query, connection);
DataTable dt = new DataTable();
connection.Open();
adapter.Fill(dt);
ExamEditGridView.DataSource = dt;
ExamEditGridView.DataBind();
}
the gridview is databound when a dropdown lists index changes, which gives me the mod_id for the query

I ended up getting it working, I didn't realize I had to set the gridview's editindex value and redatabind to toggle edit mode
code:
protected void EditExam(object sender, GridViewEditEventArgs e)
{
ExamEditGridView.EditIndex = e.NewEditIndex;
ExamEditGridView.DataSource = Session["data"];
ExamEditGridView.DataBind();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
ExamEditGridView.EditIndex = -1;
ExamEditGridView.DataSource = Session["data"];
ExamEditGridView.DataBind();
}

Related

issue in using dynamic grid link button for scriptManager.RegisterPostBackControl (control) as this has to be declared at page_load

I was trying to download csv file on grid's dynamically created link button.
I was facing issue while downloading csv in asp.net.
Exception : Sys.WebForms.PageRequestManagerParserErrorException
This Exception is resolved by using code:
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(this.grouplnkbutton);
at page_load event,but this.grouplnkbutton (dynamically created link button i.e. grouplnkbutton control is not available at page_load event).
how can i use linkbutton with scriptmanager at page_load event.
Code:
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(this.grouplnkbutton);
//codes
}
protected void hlGroupName_Click(object sender, EventArgs e)
{
try`enter code here`
{
Response.ClearHeaders();
Response.ClearContent();
grouplnkbutton = sender as LinkButton;
string linkBtnValue = grouplnkbutton.CommandArgument;
GridDataItem item = grouplnkbutton.NamingContainer as GridDataItem;
ExportToCSV exportToCSV = new ExportToCSV();
StringBuilder csv = new StringBuilder();
DataSet gridData = new DataSet();
int scheduleId = Convert.ToInt32(((HiddenField)item.FindControl("hidID")).Value);
csv = exportToCSV.ExportScheduleDataToCSV(scheduleId);
Response.Buffer = true;
Response.Clear();
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment;filename=perfscheduleReport.csv");
//Response.Charset = "";
Response.Output.Write(csv.ToString());
//Response.Write(csv.ToString());
Response.Flush();
//Response.End();
}
Thanks for solution.
markup code
<telerik:RadGrid ID="PerfGrid" GridLines="None" runat="server" CssClass="BorderGrid" OnItemDataBound="PerfGrid_ItemDataBound" OnItemCommand ="PerfGrid_ItemCommand"
Skin="Default" Width="100%" PageSize="100" PagerStyle-PageSizeLabelText="Records Per Page" AllowFilteringByColumn="true" OnNeedDataSource="PerfGrid_NeedDataSource" OnPageIndexChanged="PerfGrid_PageIndexChanged">
<ClientSettings EnableRowHoverStyle="true">
<Resizing AllowColumnResize="True" AllowRowResize="false" ResizeGridOnColumnResize="false"
ClipCellContentOnResize="true" EnableRealTimeResize="false" AllowResizeToFit="true" />
</ClientSettings>
<MasterTableView CommandItemDisplay="None" HorizontalAlign="NotSet" AllowPaging="false" AutoGenerateColumns="False" AllowSorting="true" AllowFilteringByColumn="True">
<HeaderStyle CssClass="GridHeader" Font-Bold="true"></HeaderStyle>
<ItemStyle BackColor="White" CssClass="text2" HorizontalAlign="Left" />
<AlternatingItemStyle BackColor="#E6EEF8" CssClass="text2" HorizontalAlign="Left" />
<%--<PagerStyle AlwaysVisible="true" Mode="NextPrevAndNumeric" />--%>
<Columns>
<telerik:GridBoundColumn DataField="ScheduleId" Display="false" ReadOnly="true" HeaderText="ID" AllowFiltering="false" HeaderStyle-Width="10px">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn HeaderText="Select" HeaderStyle-Width="15px" AllowFiltering="false">
<ItemTemplate>
<asp:CheckBox ID="CheckSelect" runat="server"></asp:CheckBox>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn DataField="GroupingName" ReadOnly="true" HeaderText="Group Name" SortExpression="GroupName" HeaderStyle-Width="20px">
<ItemTemplate>
<asp:LinkButton ID="hlGroupName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "GroupingName") %>' OnClick="hlGroupName_Click"></asp:LinkButton> <%--CommandName="Export"--%>
<%--<asp:HyperLink ID="hlTestCase" CommandName="Edit1" runat="server" Text='<%# Container.DataItem("TestDescription") %>'--%>
Target="_self"></asp:HyperLink>--%>
<asp:HiddenField ID="hidID" runat="server" Value='<%# CheckNull(DataBinder.Eval(Container.DataItem, "ScheduleId") , false)%>' />
<%--Value='<%# Container.DataItem("Id") %>' Value='<%# DataBinder.Eval(Container.DataItem, "Id") %>--%>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn SortExpression="TestDescription" DataField="TestDescription" ReadOnly="true" HeaderText="Test Cases" HeaderStyle-Width="30px">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn SortExpression="ServerIP" DataField="ServerIP" ReadOnly="true" HeaderText="Server IP" HeaderStyle-Width="20px">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn SortExpression="LoadNoOfUsersTobeSimulated" DataField="LoadNoOfUsersTobeSimulated" HeaderText="Users Load" ReadOnly="true" HeaderStyle-Width="12px">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn SortExpression="StartTime" DataField="StartTime" HeaderText="Start Time" ReadOnly="true" HeaderStyle-Width="25px">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn SortExpression="EndTime" DataField="EndTime" HeaderText="End Time" ReadOnly="true" HeaderStyle-Width="25px">
</telerik:GridBoundColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
in this lnkbtn - ID -"hlGroupname" onclick event i want to downalod csv
But getting Exception:Sys.WebForms.PageRequestManagerParserErrorException
resolved Exception using :
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
ScriptManager.RegisterPostBackControl(this.PerfGrid);
//codes
}
I am using Scriptmanager as my grid is under updatepanel.
Here PerfGrid is telerikGrid control. Instead of grid control i want to use dynamically created grid link button. And onclick event of lnkbutton i want to download csv.
Hum, your code looks fine, but why the need for the register script?
dump that code you have in the load event, I don't see a need for it??
You not posted your markup, but say a grid like this:
<asp:GridView ID="GridView1" runat="server" CssClass="table" AutoGenerateColumns="False" DataKeyNames="ID">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="ProjectName" HeaderText="ProjectName" />
<asp:BoundField DataField="ProjectDate" HeaderText="ProjectDate" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" OnClick="LinkButton1_Click">My Link</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Your button code then as you have looks fine.
I don't (so far) on what you posted see why any need for register script or that button event needs that code. You can just wire up the click event as you have, nothing more need be done.
So, in above, the linkbutton should be just fine. Check and REMOVE the post-back URL setting for that link button - that might be your issue (but, you not posted at least the markup you have for the LinkButton.
It should only require the click even code you have - no other settings such as post-back URL is required for that button click event to work. In fact, it not at all clear why you using a LinkButton as opposed to say a button? (I see no need for a link button ).
So, no real reason for the register script stuff - remove it.
And note how I don't have to include the PK row "ID" in the markup, or even a hidden field. The datakeys setting is just for that reason (and it nice from a secuirty point of view - I don't have to render the PK row ID has hiddefield or anything.
Hence this code can get the PK id
protected void LinkButton1_Click(object sender, EventArgs e)
{
LinkButton lBtn = sender as LinkButton;
GridViewRow gRow = lBtn.NamingContainer as GridViewRow;
// get row click index with gRow.RowIndex
int? pkID = GridView1.DataKeys[gRow.RowIndex]["ID"] as int?;
And my code to fill the gv was this:
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Project"L, conn))
{
conn.Open();
GridView1.DataSource = cmdSQL.ExecuteReader();
GridView1.DataBind();
}
Now, of course if you using the row data bound for ANY thing at all? Then don't bind the GV to the reader, but use this:
conn.Open();
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader();
GridView1.DataSource = rstData;
GridView1.DataBind();

how to insert data from grid view control when button in particular row is clicked?

I am having one friend request form.In that,I have used grid view control to show all registered members,So one who want to send request he/she can send request.My form design code is:
enter code here
<asp:GridView ID="grdviewFriendRequest" runat="server" AllowPaging="true" AutoGenerateColumns="false"
EmptyDataText="No members found" Width="100%" Font-Size="16px" ForeColor="#FF9F00"
GridLines="None" PagerSettings-Mode="NumericFirstLast"
onselectedindexchanged="grdviewFriendRequest_SelectedIndexChanged">
<FooterStyle BackColor="#FFB100" Font-Bold="true" ForeColor="#000000" />
<RowStyle BackColor="#FFD340" />
<EditRowStyle BackColor="#FFDE40" />
<SelectedRowStyle BackColor="#FFC900" Font-Bold="True" ForeColor="#000000" />
<PagerStyle BackColor="#FFEB73" ForeColor="Black" HorizontalAlign="Center" />
<HeaderStyle BackColor="#FFB100" Font-Bold="True" ForeColor="000000" HorizontalAlign="Left" />
<AlternatingRowStyle BackColor="#FFDF73" />
<Columns>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<%#Eval("firstName")%></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<%#Eval("lastName")%></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Send Friend Request">
<ItemTemplate>
<asp:Button ID="btnSendFrndReq" CssClass="btnImage" Text="Send Friend Request" runat="server" OnClick="btnSendFrndReq_Click" /></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
So,I want to do like,when user click on button in front of particular member's name,the data from that row should get store in a table.
I have tried this on button click event ,but it's not working.I am unable to find what is going wrong.I giving the code behind,Please check it,and suggest me any solution
protected void grdviewFriendRequest_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void btnSendFrndReq_Click(object sender, EventArgs e)
{
string fname = "", lname = "";
GridViewRow row = grdviewFriendRequest.SelectedRow;
fname = row.Cells[0].Text;
lname = row.Cells[1].Text;
Int32 frmCandiid = (Int32)(Session["candiID"]);
InsertRegistation frndRq= new InsertRegistation();
Session["candID"] =frndRq.FrndReqGetCandiid(fname, lname);
Int32 toCandiid = (Int32)(Session["candID"]);
frndRq.InsertFrndReq(0, frmCandiid, toCandiid, DateTime.Now);
}
But after I try this i.e
enter code here
protected void grdviewFriendRequest_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "SendFriendReq")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = grdviewFriendRequest.Rows[index];
string fname = "", lname = "";
fname = row.Cells[0].Text;
lname = row.Cells[1].Text;
Int32 frmCandiid = (Int32)(Session["candiID"]);
InsertRegistation frndRq = new InsertRegistation();
Session["candID"] = frndRq.FrndReqGetCandiid(fname, lname);
Int32 toCandiid = (Int32)(Session["candID"]);
frndRq.InsertFrndReq(0, frmCandiid, toCandiid, DateTime.Now);
}
}
it gives me error, saying Input string not in a correct form.
then I try to give commandArgument property,but still it gives me value 0;
<asp:TemplateField HeaderText="Send Friend Request">
<ItemTemplate>
<asp:Button ID="btnSendFrndReq" CssClass="btnImage" Text="Send Friend Request" runat="server" CommandName="SendFriendReq" CommandArgument="<%# Container.DataItemIndex %>" /></ItemTemplate>
</asp:TemplateField>
and also tell me what value should be supply to command argument.
So,what I can do now?
It doesn't look like you actually need a command argument.
What you need is to find the row the clicked button was in.
And it happens you can just do this with the NamingContainer of the button (Control) propery.
var MyRow = (GridViewRow)((Control)sender).NamingContainer;
var usefullTextBox = (TextBox)MyRow.FindControl("usefullTextBox"); // Yes, the name is made up.
....
DoWhatYouWant(usefullTextBox.Value);

Updating gridview row is not saving the data

I am having issue when updating gridview! everything is seems to be working. but when i hit finish editing the data will not save!
but when i click edit the correct fields prompt me to enter new value but it wont save!
here is my asp
<asp:GridView ID="GridView1" runat="server" CssClass="report"
AutoGenerateColumns="False" onrowediting="GridView1_RowEditing"
DataKeyNames="TimeID" onrowupdating="GridView1_RowUpdating"
onrowcommand="GridView1_RowCommand"
onrowcancelingedit="GridView1_RowCancelingEdit">
<Columns>
<asp:BoundField DataField="date" Visible="true" ReadOnly="true" HeaderText="Date" />
<asp:BoundField DataField="Description" HeaderText="Stage Description" ReadOnly="True" />
<asp:TemplateField HeaderText="Start Time">
<ItemTemplate>
<asp:Label ID="Label7" runat="server" Text='<%# ConvertToShotTime(Eval("StartTime")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtStartTime" ValidationGroup="1" Width="90px" class="TimeEntry" runat="server" Text='<%# ConvertToShotTime(Eval("StartTime")) %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" ControlToValidate="txtStartTime" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="End Time">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# ConvertToShotTime(Eval("EndTime")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEndTime" class="TimeEntry" ValidationGroup="1" Width="90px" runat="server" Text='<%# ConvertToShotTime(Eval("EndTime")) %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator66" ControlToValidate="txtEndTime" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TimeInHours" HeaderText="Time Time (Hours)" ReadOnly="True" />
<asp:CommandField ShowEditButton="true" ShowCancelButton="true"
ButtonType="Image" EditImageUrl="~/images/edit_record.jpg"
CancelImageUrl="~/images/edit_no.jpg"
UpdateImageUrl="~/images/update_record.jpg" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="lnbCopy" runat="server" AlternateText="Delete"
CommandName="DeleteRecord" CommandArgument='<%# Bind("TimeID") %>' OnClientClick="return confirm('Are you sure you want to delete this row?');" ImageUrl="~/images/delete_record.jpg" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblTimeID" runat="server" Text='<%# Eval("TimeID") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here is what i have done in behind code
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) {
GridView1.EditIndex = e.NewEditIndex;
loadTable();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) {
GridView1.EditIndex = -1;
loadTable();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) {
GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;
var StartTime = row.FindControl("txtStartTime") as TextBox;
var EndTime = row.FindControl("txtEndTime") as TextBox;
var id = row.FindControl("lblTimeID") as Label;
SqlConnection conn = new SqlConnection(conStr.GetConnectionString("myServer1"));
SqlCommand comm = new SqlCommand();
comm.CommandText = "UPDATE CDSTimeSheet SET StartTime = #StartTime, EndTime = #EndTime ,timeElapsed = datediff(minute,#startTime , #EndTime), timeInSeconds = datediff(second,#startTime , #EndTime) WHERE TimeID = #id";
comm.Connection = conn;
comm.Parameters.AddWithValue("#id", id.Text);
comm.Parameters.AddWithValue("#StartTime", StartTime.Text);
comm.Parameters.AddWithValue("#EndTime", EndTime.Text);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
GridView1.EditIndex = -1;
loadTable();
}
what am i doing wrong?
It sounds a lot like you are not calling DataBind on your grid after updating the underlying data. After you perform the update (possibly within the loadTable method that I see referenced up there), call
GridView1.DataBind();
That should refresh the data in the grid.
After your comments, I see that you're not using the NewValues collection in the GridViewUpdateEventArgs parameter to get the actual incoming, updated field values. Try this:
String StartTime = e.NewValues["StartTime"].ToString();
String EndTime = e.NewValues["EndTime"].ToString();
String id = e.Keys[0].ToString();
Note that these variables are strings now, not TextBoxs, so you don't need to add ".Text" on them when you add them as parameters.
Handle the postback, basically if you fill the grid view in each postback you are re filling the gridview with old data, that's why you retrieve data with no changes (remember after Update button this trigger a postback). So, in case this is your case, try this.
if(!this.IsPostback)
{
(Method that fills your GridView)
}

GridView DataBind does not work

I am using ASP.NET Membership and Linq. I have a problem here: I show all users inside a grid view that has a delete button. Take a look at this code:
<asp:GridView
ID="UsersGridView"
runat="server"
AutoGenerateColumns="False"
DataSourceID="UsersLinqDataSource"
AllowPaging="True">
<Columns>
<asp:BoundField DataField="UserName" HeaderText="UserName" ReadOnly="True" SortExpression="UserName" />
<asp:BoundField DataField="LastActivityDate" HeaderText="LastActivityDate" ReadOnly="True" SortExpression="LastActivityDate" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="DeleteButton" runat="server" CommandArgument='<%# Eval("UserName") %>' Text="Delete" OnClick="DeleteButton_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:LinqDataSource
ID="UsersLinqDataSource"
runat="server"
ContextTypeName="TraceWeb.DataModel.DataContextDataContext"
EntityTypeName=""
Select="new (UserName, LastActivityDate)"
TableName="Users"
EnableDelete="True">
</asp:LinqDataSource>
And Delete button's event handler:
protected void DeleteButton_Click(object sender, EventArgs e)
{
String username = (String)((sender as IButtonControl).CommandArgument);
Membership.DeleteUser(username, true);
UsersGridView.DataBind();
}
But problem is that after running this code and deleting a user, GridView still shows that user.
This happens because Membership and UsersLinqDataSource are not connected and if you "refresh" the UsersLinqDataSource status and then rebind your grid, all will be displayed properly.
protected void DeleteButton_Click(object sender, EventArgs e)
{
String username = (String)((sender as IButtonControl).CommandArgument);
Membership.DeleteUser(username, true);
// first solution: may not work properly
UsersLinqDataSource = yourLinqData;
// second solution: work
UsersLinqDataSource = null;
UsersLinqDataSource = yourLinqData;
UsersGridView.DataBind();
}

Get Gridview dropdownList value

work on asp.net vs05.I have a grid
<asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False"
DataKeyNames="StudentID" OnSelectedIndexChanged="GridView3_SelectedIndexChanged"
OnRowDataBound="GridView3_RowDataBound">
<Columns>
<asp:BoundField DataField="StudentID" HeaderText="StudentID" ReadOnly="True"
SortExpression="StudentID" />
<asp:BoundField DataField="StudentName" HeaderText="StudentName" />
<asp:TemplateField HeaderText="DivisionName">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"
Text='<%# Bind("StudentName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
Width="160px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField ButtonType="Button" CommandName="Select" HeaderText="Update"
Text="Update" />
</Columns>
</asp:GridView>
Using The button Click i want to save value on database.But i can not read value from the dropdownlist
protected void GridView3_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow selectRow = GridView3.SelectedRow;
String ID = selectRow.Cells[0].Text;
String Name = selectRow.Cells[1].Text;
//String Dis = selectRow.Cells[2].Text;
String Dis =
((DropDownList)sender).FindControl("DropDownList1").ToString();
//**want to get this value**
}
How can i get ddl selected value?i want to put the object of a class on ddl .Bellow code work on desktop ,Want same thing on web.
DropDownList1.DisplayMember = "CommercialRegionName";
foreach (class oItem in _collection)
{
DropDownList1.Items.Add(oItem);
//**want to save object,Not any object item like:oItem.Name.**
}
protected void GridView3_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow selectRow = GridView3.SelectedRow;
String ID = selectRow.Cells[0].Text;
String Name = selectRow.Cells[1].Text;
//String Dis = selectRow.Cells[2].Text;
//PROBABLY YOU WANT TO GET ITEM FROM SELECTED ROW'S DROPDOWN
var ddl = (selectRow).FindControl("DropDownList1") as DropdownList;
if(dis!=null){
var s=ddl.SelectedItem.Text;
}
}

Resources