Equivalent of e.ReturnValue in EntityDataSource - asp.net

I'm using EntityDataSource with DetailsView in my ASP.NET application. I want to get identity column value after inserting the record. ObjectDataSource has e.ReturnValue property I want to know its equivalent in EntityDataSource?

You can subscribe to the Inserted event, which is an EventHandler<EntityDataSourceChangedEventArgs>.
The EntityDataSourceChangedEventArgs instance has an Entity property, representing the newly inserted entity.
void EntityDataSource1_Inserted(object sender, EntityDataSourceChangedEventArgs e) {
YourEntityType newlyAdded = (YourEntityType)e.Entity;
int newId = newlyAdded.Id;
}

Related

How to edit gridview row inside?

I want to edit row of gridview.For that, I have added showeditbutton = true.I have binded gridview from cs file.Does I need to wite 3 function for that?(For editing I have added 3 function in cs file.).I have taken help from internet.But some point did not understand.
--In aspx
<asp:GridView datakeyname="Id" Id ="Gridview1" onRowEditing="GridView1_RowEditing" RowCancelingEdit=" GridView1_RowCancelingEdit" onRowUpdating ="GridView1_RowUpdating" >
<column>
// hyperlink ,dataTextfield is id
// some checkboxfield.(start from column 6)
</column>
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
//code for Binding grid
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// for fetching value of id and checkboxfield(column 6)
string Id= GridView1.DataKeys[e.RowIndex].Values["Id"].ToString());
bool ischeck = (Gridview1.Rows[e.RowIndex].Cells[5].Controls[0] as checkBox).Checked;
// code for updating grid
GridView1.EditIndex = -1;
//Now bind the gridview gain here
}
protected void GridView1_RowCancelingEdit(object sender, GridViewUpdateEventArgs e)
{
GridView1.EditIndex = -1;
//Now bind the gridview gain here
}
Does am I going in right direction?What is use of datakey.Does I used properly?Why GridView1.EditIndex = -1 in update and cancel event.Column 6 is checkboxfield.why .Controls[0] is used for accessing that checkboxfield.
If you are using an ObjectDataSource (or SqlDataSource or OleDbDataSource) to databind and use UpdateCommand, DeleteCommand, InsertCommand, then you do not need to explicitly write those three functions for the edit/update operation. You need those functions when you are writing the binding code in code-behind or if you want to do additional work before/after any operation.
RowEditing fires when you click "edit" on the GridView. Here you specify what row to open in editmode by writing GridView1.EditIndex = e.NewEditIndex. You can also write code here to do any work that is required before user is put into editmode. For example, you can check for business rules conditions, and cancel the operation if rules are not met.
RowUpdating fires when you click "save"/"update" on the GridView. This is fired before the actual database operation. If you have an UpdateCommand on the datasource, then you do not need to write database save routine, otherwise you write that here.
DataKeys identify the "key" that identifies the data that is bound. You specify DataKeys while databinding to the GridView. For example, primary key of a database table. This line: string Id= GridView1.DataKeys[e.RowIndex].Values["Id"].ToString()); Here you are picking up the value of the "Id" key (you can have more than one keys) of the current row.
GridView1.EditIndex = -1 in update or cancel specifies that the GridView should no longer be in editmode. If this value is >= 0, then the GridView is put into editmode for that row (index starting from 0). So we set it to -1, to indicate that it should not be in editmode.
Controls[0] is used to pick the first control in that cell (you may have more than one controls). Alternatively, you can also use FindControl.

Sorting a gridview using a datatable, and datasource that is an ArrayList

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx
This article deals with creating a datatable first, then creating a gridview from it, to aid in sorting. My predicament is slightly different.
I have a Gridview, that on Page_Load, I set the datasource to an ArrayList, and bind.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.GridView1.DataSource = RequestManager.Instance.GetAllRequests();
this.GridView1.DataBind();
}
}
Now I would like to sort this GridView, so on the aspx page, I set AllowSorting="true", and OnSorting="GridView1_Sorting". So far, so good. I have the SortExpressions set in the BoundFields, and when I click on it, I know the _Sorting event is triggered.
Now, since this is a postback operation, I cannot simply cast the datasource of the gridview to a DataTable to sort. Saving to ViewState is an option, but I cannot figure out how to do it.
I would like to use the simple solution on this page, except for the DataTable not being available to me. Thanks for looking.
If you're able to target .NET v3.5, I recommend using Linq. In your _Sorting event handler, get the array list you did in the Page_Load and rebind it.
For example, if the type contained in the array list are MyType instances that have properties named Default and SomeField:
protected void Grid_Sorting(object sender, GridViewSortEventArgs e)
{
Func<MyType, object> keySelector;
if(e.SortExpresion == "SomeField")
{
keySelector = dataItem => dataItem.SomeField;
}
else
{
keySelector = dataItem => dataItem.Default;
}
ArrayList dataItems = RequestManager.Instance.GetAllRequests();
this.GridView1.DataSource = dataItems.OfType<MyType>().OrderBy(keySelector);
this.GridView1.DataBind();
}
That will get you started, then later inspect the sort expression to see if it ends with ASC or DESC and conditionally call .OrderByDescending(keySelector).
Finally, I don't recommend stashing the list in ViewState, as the ObjectStateFormatter is only optimized for a handful of types. http://msdn.microsoft.com/en-us/library/system.web.ui.objectstateformatter.aspx
Maybe consider ASP.NET cache instead.

Pass Key of Grid to Business Class via Object Data Source

In ASP.NET Webforms have an ASP.NET GridView connected to a C# class via an object data source
I have an ID set up as a DataKeyName in the grid. How do I pass this to the C# class when I update the grid?
Can pick up the grids data key name for the current row in the grids row updating event
protected void gvSearchResults_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//get handle on current grid row
DataKey keys = gvSearchResults.DataKeys[e.RowIndex];
customerId= GeneralUtils.GetIntegerKeyValue(keys, "customerID");
}
Then pass it to C# class using object data sources updating event
protected void odsHauliers_Updating(object sender, ObjectDataSourceMethodEventArgs e)
{
e.InputParameters["customerID"] = this.customerID;
}
Actually data key names are passed automatically by the datagrid to the object data source.

Making GridView Respond to 2 Drop Down Lists

I have got 2 DropDownLists on my Form and 1 GridView. I want the GridView to display the data according to the selection from the DropDownLists.
For Example, One DropDownList contains Names and another contains Dates. Both the DropDownLists can post back. So if I select a name from 1st DropDownList, the GridView should show all the results according to that Name. Similarly if i select the Date from the other DropDownList , the GridView should show the results according to the dates. But i cant figure out as how to bind GridView to respond to 2 DropDownList.
BTW i am binding both the Drop Down Lists and the Grid View to the DataSource Objects, which is getting data from the database.
Any Suggestions??
It's better and cleaner if You use two DataSource with selecting data from db, and binding each of them to the DropDownList. I tried in my ASP.NET app do what You want but unfortunatelly I have erorrs :/
My only sollution is to don't use DataSouce in aspx file, but in DropDownList SelectedItem event use DataContext and it's possible that then you could bind both to the same DataView like below. I am not sure, but maybe You must use null in DataSource to reset GridView before use new data source:
protected void btPokaz_Click(object sender, EventArgs e)
{
DataClassesDataContext db = new DataClassesDataContext();
var DzieciGrupa = from p in db.Dzieckos
where p.Grupy.Numer == Convert.ToInt32(this.dropListGrupy.SelectedValue)
orderby p.Nazwisko
select new { p.Imie, p.Nazwisko };
if (DzieciGrupa.Count() == 0) this.Label1.Text = "W " + this.dropListGrupy.SelectedValue.ToString() + " grupie nie ma dzieci zapisanych!";
this.GridGrupy.DataSource = null;
this.GridGrupy.DataSource = DzieciGrupa;
// this.GridView1.DataSourceID = String.Empty;
this.GridGrupy.DataBind();
Try it and tell say that works ;)
For Your problem You should create dwo EDM class for each data source. And simple in DDL select event Your choose of DataContext depends from user choose in DDL.
Example :
protected void DDL_SelectedItem(object sender, EventArgs e)
{
TypeOfQueryData query = null;//you must know what type is data You query
if(this.dropListGrupy.SelectedValue==someItemSelect)
{
DataClasses1DataContext db = new DataClasses1DataContext();
//query to get data from source
query= from p in db.Dzieckos
where p.Grupy.Numer == Convert.ToInt32(this.dropListGrupy.SelectedValue)
orderby p.Nazwisko
select new { p.Imie, p.Nazwisko };
}
if(this.dropListGrupy.SelectedValue==otherItemSelect)
{
DataClasses2DataContext db = new DataClasses2DataContext();
query= from p in db.Dzieckos
where p.Grupy.Numer == Convert.ToInt32(this.dropListGrupy.SelectedValue)
orderby p.Nazwisko
select new { p.Imie, p.Nazwisko };
}
this.GridGrupy.DataSource = null;
this.GridGrupy.DataSource = DzieciGrupa;
// this.GridView1.DataSourceID = String.Empty;//maybe You need do that
this.GridGrupy.DataBind();

ASP.net list of dropdownlists - similar to Access continuous form

What I'm looking for is a way to mimic the MS-Access style continuous form within asp.net. In one particular case, I want a control, bound to a datasource which returns a dropdownlist for each row, bound to the value within the datasource. Any change to any of the dropdownlists' would perform an update to the database instantly.
I have got halfway to achieving this using a repeater control, with the DropDownList.SelectedValue assigned within the Repeater.ItemDataBound event.
But now, supposing I add an OnSelectedIndexChanged event to the DropDownList - how would I then query the repeater to know which row I was on (to get the primary key value, for example)
I'm not sure this can be done easily.. so the question is what should I really be doing? I don't want to use a GridView that requires me to select a row to edit.. I just want to have the dropdownlists autopostback for any updates.
Hope that's clear?!
Cheers! :D
For examples sake, lets say we are binding to a custom class called Record
public class Record
{
public int Id;
public string Value;
}
If you put custom logic on the Repeater.OnItemCreated event you can attach the primary key to the id of the drop down list
protected void Repeater_ItemCreated(object sender, RepeaterItemEventArgs e)
{
if (!(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem))
return;
var dataItem = e.Item.DataItem as Record;
if (dataItem == null) return;
var dropdown = e.Item.FindControl("myDropDown") as DropDownList;
if (dropdown == null) return;
dropdown.ID = dropdown.ID + dataItem.Id;
}
Then on the SelectedIndexChange, you can pull the id off of the dropdown that fired the event.
protected void SelectedIndexChanged(object sender, EventArgs e)
{
var dropdown = sender as DropDownList;
if (dropdown == null) return;
var stringId = dropdown.ID.Replace("myDropDown", "");
int id;
if (Int32.TryParse(stringId, out id))
{
updateRecord(id, dropdown.SelectedValue);
}
}
It's very much an ugly hack, but it should allow you to do what you want.
Easiest way to tackle this would be to mimic the Access continuous form ASP.NET style. Which would be to make a UserControl to handle the row-level UI, then put said UserControl in a repeater.

Resources