I have a listbox inside of a gridview which appears when you click edit, it has a list of event types which you can select multiple. I cannot figure out how to update my entity when the update button is clicked. I need to be able to update the entity collection with the selection made from the listbox inside the gridview. The gridview is using an entity datasource. Below is the list box in the gridview.
<asp:TemplateField HeaderText="Event Type">
<ItemTemplate>
<asp:Label runat="server" ID="eventTypeLabel" Text="<%#VenueExplorer.Utilities.StringUtils.convertEventsToCommaString(Container.DataItem) %>" />
</ItemTemplate>
<EditItemTemplate>
<asp:ListBox ID="eventListbox" runat="server" DataSourceID="eventTypeDataSource" DataValueField="EventTypeID" DataTextField="EventType" SelectionMode="Multiple"></asp:ListBox>
</EditItemTemplate>
</asp:TemplateField>
Is there a way I can update the entity binded to the gridview before the actual save is performed?
During the RowUpdating event of your GridView, you can capture the ListBox's selected values.
Without knowing your full markup or database structure, I can only mock up the intended code. Something like this, though you'll obviously have to modify it to suit your needs:
protected void grdView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
ListBox eventListbox = (ListBox)grdViewName.Rows[e.RowIndex].Cells[ZeroBasedCellNumberOfTheListBox].FindControl("eventListbox");
// Retrieve the currently selected entity (row) from the database
ParentEntity yourParentEntity = from entity in DataContext.ParentEntity where entity.ID == grdViewName.Rows[e.RowIndex].Cells[IndexOfYourEntitysID].Text;
foreach (ListItem item in eventListbox.Items)
{
if (item.Selected)
{
EventType eventType = new EventType();
eventType.ID = item.Value;
eventType.Name = item.Text;
yourParentEntity.EventTypes.Add(eventType); }
}
DataContext.Commit();
}
Related
So I have a GridView for a C# web application, that has a Buttonfield, and when that button is clicked, I need to get the value of one of the fields for that row and store it in a variable for processing in some way.
However, neither the GridView nor the ButtonField seem to possess any means of doing this.
Can anyone recommend a way of getting data from a GridView, or if this is not possible, a different type of view that does offer this functionality, while still displaying a whole table (eg, not a DetailsView)
You can Check this link: https://msdn.microsoft.com/en-us/library/bb907626(v=vs.140).aspx.
Define the CommandName of the Button.
In the GridView Define the RowCommand Event and Check the CommandName.
Get the Index of the Row.
Get the Column with GridView.Rows[index](columnIndex)
If you are using asp:TemplateField like shown below then you can access the row content using RowCommand
Markup
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCode" runat="server" Text='<%# Eval("CustomerID") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="AddCode" Text="Add New"/>
Code
protected void gvwSearch_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "AddCode")
{
var clickedButton = e.CommandSource as Button;
var clickedRow = clickedButton.NamingContainer as GridViewRow;
var rows_lblCode = clickedRow.FindControl("lblCode") as Label;
// now you can acccess all the label properties. For example,
var temp = rows_lblCode.Text;
}
}
I have a gridview which gets populated with the help of a sqldatasource.
Once the gridview is created I want to add a manual column created Notes so that the user can enter notes for each row and then click the submit the form.
In the <Columns> field of the grid view I have this:
<asp:TemplateField HeaderText="Notes">
<ItemTemplate>
<asp:TextBox ID="txtNotes" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
This actually creates the new column just fine but when I enter data in the textboxes it disappears when clicking submit.
In the submit even I iterate through each gridview row like so:
foreach (GridViewRow row in gvResults.Rows)
{
row.Cells[0].Text =
...
string notes = (row.Cells[10].FindControl("txtNotes") as TextBox).Text;
}
So the string notes is always empty, it seems that on postback the value is reset; because it recreates the txtNotes textbox.
How can I keep the value on postback?
When you bind the GridView, make sure you check to see if it's a postback.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
LoadData(); //if you did this without checking IsPostBack, you'd rebind the GridView and lose the existing rows
}
protected void LoadData()
{
//bind GridView etc
}
I have an ASP.NET GridView which amongst other values binds an ID to one of the columns.
Another one of the columns of this table should contain a list of items, which should be resolved by passing in the ID from the GridView.
To achieve this, I tried nesting the ListView inside the GridView, and passing the ID into the Default Parameter of an ObjectDataSource used by the ListView, but this syntax is not allowed:
<asp:TemplateField HeaderText="columnItems">
<ItemTemplate>
<asp:ListView ID="listOfItems" runat="server" DataSourceID="MyObjectDataSource >
<ItemTemplate>
<asp:LinkButton ID="MyLinkButton" Runat="Server" Text='item'></asp:LinkButton>
</ItemTemplate>
</asp:ListView>
<asp:ObjectDataSource ID="MyObjectDataSource" runat="server"
TypeName="MyTypeName.Whatever" SelectMethod="GetItems">
<SelectParameters>
<asp:Parameter Name="requestId" Type="String" DefaultValue='<%# Eval("ID")'/>
</SelectParameters>
</asp:ObjectDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
So how do I go about passing in the ID so I can get the list of items?
You probably need to do that in the RowDataBound event, get the ID there and then do you DB
then do something like
if(e.Row.RowType != DataControlRowType.DataRow)
{
return;
}
ListView a = (ListView)e.Row.FindControl("listOfItems");
a.datasource = // the result of your db call
a.databind();
Attach a 'OnRowDataBound' event to the GridView control to retrieve the items for the ListView for each row on the GridView (after the GridView has been bound):
e.g. On the ASPX page:
<asp:GridView id="MyGridView" OnRowDataBound="GetItems" ... > ... </asp:GridView>
In the code-behind:
protected void GetItems(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow)
{
return;
}
// Get the ID from the GridView
var dataRowView = (DataRowView) e.Row.DataItem;
var id = dataRowView["ID"].ToString();
// Bind the supporting documents to the ListView control
var listView = (ListView) e.Row.FindControl("listOfItems");
listView.DataSource = /* Call to database to return a DataSet of items */;
listView.DataBind();
}
(As would be appropriate, I tried editing Tunisiano's post to elaborate on his answer on attaching the event to the GridView and getting the request ID, but SO editors are rejecting it for no good reason. The above code is tested and answers the question exactly).
I want to create a dynamic gridview with first row as drop down on clicking edit button. I dont have any idea on how to start. Can you please help. I have gone through some articals and found using the InstantiateIn method we can achieve.
public class CreateItemTemplate : ITemplate
{
//Field to store the ListItemType value
private ListItemType myListItemType;
public CreateItemTemplate(ListItemType item)
{
myListItemType = item;
}
public void InstantiateIn(System.Web.UI.Control container)
{
//Code to create the ItemTemplate and its field.
if (myListItemType == ListItemType.Item)
{
TextBox txtCashCheque = new TextBox();
container.Controls.Add(txtCashCheque);
}
}
}
If you want to display this on a single page, you should not be creating a server control.
Use the grid's TemplateField.
Note: if you are using AutoGenerateColumns = true, just add the column to the grid markup. It will be added first.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList id="someId" runat="server">
<asp:ListItem Text="One" />
<asp:ListItem Text="twO" />
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
you may need to provide more information about what you want to do wth this drop down (does it need a default value?).
Based on your needs, you may be able to do this in markup, or, you may need to use a grid event.
Brian
UPDATE: adding event handler
if you set onrowcreated="GridView1_RowCreated" in the grid
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"
onrowcreated="GridView1_RowCreated">
and do this in your code behind:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var dropdown = e.Row.FindControl("someId") as DropDownList;
//dropdown.DataSource= <>; bind it
//dropdown.SelectedValue =<>"; / set value how you would
}
}
you can manipulate the drop down ad it gets created.
If it cannot fin the controls look in each cell: e.Row.Cells[[index]].FindControl(""someId"")
I have two GridView in ASP.net 3.5 page. I have HyperLink field as one of the fields in the First GridView.
On click of this hyperlink I need to call display the 2nd grid by passing some values to a method showAllRecords(value from hyperlink)
How do I do this?
Thanks
You can try a TemplateField like this for GridView1 (primary GridView)
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="LinkButton1" CommandName="cmdName" CommandArgument='<%# Eval("IdColumn") %>' > LinkButton</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
and in GridView1's RowCommand, you can get the CommandArgument and setup the DataSource for GridView2 (child GridView).
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName = "cmdName")
{
var arg = e.CommandArgument;
// use arg to filter GridView2's DataSource
GridView2.DataSource = FilteredDataSource;
GridView2.DataBind();
// show GridView2 if it's hidden.
}
}
Maybe the following blog post could give you a hint;
http://www.tugberkugurlu.com/archive/parent-child-view-in-a-single-table-with-gridview-control-on-asp-net-web-forms
First you need to handle SelectedIndexChanged event on the first grid and then get the value from the hyperlink. Is the hyperlink a DataKey? If it is then you get it by GridOne.SelectedDataKey.Values["key"] otherwise get the actual cell by valuefromGridOne = GridOne.SelectedRow.Cells[num].Text where number is the cell number. Once you have it you can pass the value to your second grid by handling Selecting event of the objectDataSource (assuming you use it to bind data) and passing the value like this e.InputParameters["dataKey"] = valuefromGridOne;