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.
Related
I want to Populate Windows Services information in Listview using c# in a webform.
I worked on Grideview, where we bind the data source(returned as datatable from DB) with the gridview directly.
I tried similar approach using Listview, where I wanted to return the list of services and bind to Listview on Submit button function.
Problem here is - ListViewItem and ListViewDataItem doesn't take 0 arguments.
protected void submit_Click(object sender, EventArgs e)
{
string machinename = computername.Text.ToString();
ServiceDetailsListView.DataSource = GetServiceDetails(machinename);
ServiceDetailsListView.DataBind();
}
protected IEnumerable<ListViewItem> GetServiceDetails(string machinename)
{
ListViewItem serviceslist = new ListViewItem();
ServiceController[] services = ServiceController.GetServices(machinename);
foreach (ServiceController service in services)
{
//DataRow dtrow = serviceslist.NewRow();
//serviceslist.Rows.Add(service);
ListViewDataItem newListViewItem = new ListViewDataItem();
newListViewItem.Text = service.ServiceName;
newListViewItem.SubItems.Add(service.Status.ToString());
RegistryKey regKey1 = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\services\\" + service.ServiceName);
newListViewItem.SubItems.Add(regKey1.GetValue("ImagePath").ToString());
newListViewItem.SubItems.Add(regKey1.GetValue("Description").ToString());
regKey1.Close();
serviceslist.Items.Add(newListViewItem);
}
return serviceslist;
}
You may try the following:
http://weblogs.asp.net/scottgu/archive/2011/09/06/web-forms-model-binding-part-1-selecting-data-asp-net-vnext-series.aspx
It uses GridView instead of using ListView. GridViews are recommended as they offer more features that you may want to add later on e.g. Paging, Sorting, Filtering etc.
Alternately, you can use a concrete class instead of using a ListViewItem class returning IEnumerable of your new class. Later in the aspx you may using Data binding constructs like #Eval explained here:
Binding a List<> to a listview in asp.net c#
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.
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.
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;
}
I have that code in my page :
public partial class Utworz : System.Web.UI.Page
{
private List<Codes> Codes;
protected void Page_Load(object sender, EventArgs e)
{
this.GridView1.DataSource = Codes;
Codes = new List<Codes>();
}
protected void btn_AddKodManually_Click(object sender, EventArgs e)
{
Codes.Add(new Codes(code: this.TextBox1.Text, codeType: this.DropDownList1.SelectedValue));
this.GridView1.DataBind();
}
}
My page contains UpdatePanel in which I have form. I type data in this form and add to GridView.
and problem is that every time when I call Click method my Page was create new, and my variable Code also. Why this variable not save his state ?
Problem #1: The Codes variable is getting set to a new object every time the page loads. It will never have more than one code.
Problem #2: There is nothing here to hold the value of the Codes list from page view to page view. You need to store it somehow and retrieve it every time you want to rebind. For example, create a property called Codes and store the value in the viewstate. After adding a new code, rebind the grid.
I understand that you might expect the grid to hold it's state, but you're rebinding with a new object every time. Someone else might chime in here, but you may be able to restore the Codes object by calling:
Codes = this.GridView1.Datasource