GridView Row to Object Type - asp.net

In ASP.NET, if I databind a gridview with a array of objects lets say , how can I retrieve and use foo(index) when the user selects the row?
i.e.
dim fooArr() as foo;
gv1.datasource = fooArr;
gv1.databind();
On Row Select
Private Sub gv1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv1.RowCommand
If e.CommandName = "Select" Then
'get and use foo(index)
End If
End Sub

If you can be sure the order of items in your data source has not changed, you can use the CommandArgument property of the CommandEventArgs.
A more robust method, however,is to use the DataKeys/SelectedDataKey properties of the GridView. The only caveat is that your command must be of type "Select" (so, by default RowCommand will not have access to the DataKey).
Assuming you have some uniqueness in the entities comprising your list, you can set one or more key property names in the GridView's DataKeys property. When the selected item in the GridView is set, you can retrieve your key value(s) and locate the item in your bound list. This method gets you out of the problem of having the ordinal position in the GridView not matching the ordinal position of your element in the data source.
Example:
<asp:GridView ID="GridView1" runat="server" AutoGenerateSelectButton="True"
DataKeyNames="Name" onrowcommand="GridView1_RowCommand1"
onselectedindexchanged="GridView1_SelectedIndexChanged">
</asp:GridView>
Then the code-behind (or inline) for the Page would be something like:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
// Value is the Name property of the selected row's bound object.
string foo = GridView1.SelectedDataKey.Value as string;
}
Another choice would be to go spelunking in the Rows collection of the GridView, fetching values a column at a time by getting control values, but that's not recommended unless you have to.
Hope this helps.

in theory the index of the row, should be the index of foo (maybe +1 for header row, you'll need to test). so, you should be able to do something along these lines
dim x as object = foo(e.row.selectedIndex)
The other alternative is to find a way to databind the index to the commandArgument attribute of the button.

There's probably a cleaner way of doing this, but you could set the CommandArgument property of the row to its index. Then something like foo(CInt(e.CommandArgument)) would do the trick.

Related

Gridview Linkbutton Code behind

Until now, I was working with VS 2003 and recently migrated to VS 2008. I am facing some peculiar problems.
In Vs 2003,I had a Datagrid, and one of the field was ButtonField(Link button). It was not a template field. The user clicks on the field and some data gets generated.
I have written a code, in Vb, like this, on dg_ItemCommand:
Strid = Ctype(e.commandsource,linkbutton).text
Now i want to use same method,for the gridview (I think datagrid is gridview in 2008). I wrote a code like this on dg_Rowcomand
Private Sub dgSampleCustomer_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles dgSampleCustomer.RowCommand
Try
Dim strid As String
Dim i As Integer
strid = CType(e.CommandSource, LinkButton).Text
...
It is throwing a error.
Unable to cast object of type 'System.Web.UI.WebControls.GridView' to
type 'System.Web.UI.WebControls.ButtonField'.
Can anybody help me out!
It looks like the source of the command is the GridView itself, not the button you are clicking. What you probably want to do is set this value you are looking for in the "CommandArgument" property of the Linkbutton. The markup would look something like this:
<asp:LinkButton ID="myLinkButton" runat="server"
CommandName="MyCommandName"
CommandArgument="MySpecialValue"
Text="Click Me" />
Then in the event you would simply:
' strid = "MySpecialValue"
strid = e.CommandArgument.ToString()
Instead of pulling the ID from the name of the control, you can now easily get it from the command. CommandName is optional in this particular case, but comes in handy if you have multiple buttons on a grid that do different things, such as "Edit" and "Delete". Then you can use the command name to handle each command in their own way in the same event:
If (e.CommandName = "Edit") Then
' Do Some Edit Code
End If
I'm wondering why you are trying to cast the command source to a LinkButton? If you would like to attach or otherwise send some kind of row-specific information to your button handler, you are able to do this with the CommandName and CommandArgument attributes of the ButtonField.
Like:
<asp:Gridview ID="...">
...
<columns>
<asp:buttonfield buttontype="Link"
commandname="Generate"
text="Generate"/>
...
</columns>
</asp:GridView>
This will be retrievable in the event handler by using:
if(e.CommandName=="Generate")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
string rowIndex = Convert.ToInt32(e.CommandArgument);
...
}
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx
UPDATE: (use DataKeys)
Since e.CommandArgument returns a row index, and you want the ID, use the DataKeys collection, first add your ID column to the DataKeyNames collection...
<asp:GridView ... DataKeyNames="ID">
... and then retrieve the values from the DataKeys collection, like:
GridView sourceGridView = (GridView) e.CommandSource;
rowIndex = Convert.ToInt32(e.CommandArgument);
strID = sourceGridView.DataKeys[rowIndex]["ID"];
You can try this in your rowcommand event
Dim index = Convert.ToInt32(e.CommandArgument)
Dim row = dg.Rows(index)
'find your linkbutton in template field (replace "lnkBtn" with your's)
Dim myLinkButton = CType(row.FindControl("lnkBtn"), LinkButton)
Dim strid As String = myLinkButton.Text
Let me know if it helps.

Replace detailview field before insert

Is there a way to edit an hidden field value of detailsview before inserting? I want to replace it with another value. Which event can I use?
You can use ItemInserting event.
It can be done on the ItemInserting event of the DetailsView control. Here's how:
Private Sub DetailsView1_ItemInserting(sender As Object, e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles DetailsView1.ItemInserting
e.Values("ProductName") = "Your New Value"
End Sub
Basically e.Values is a collection of ordered KetValuePairs which contain your DetailsView insert form entries. You can reference them by index or by key. In the example above I reference them by key - "ProductName" in my case since I used the Products table of the Northwind database. Hope this helps...

Why is My GridView FooterRow Referencing the Wrong Row?

I have a GridView and, using a fairly common method, I'm using a FooterRow and TemplateFields to provide the missing insert ability. So far so good.
The footer contains a TemplateField with a LinkButton to provide the postback that does the insertion. In the handler for the LinkButton's click, the Insert() method is called on the ObjectDataSource that the GridView is bound to. The ObjectDataSource's insert parameters are populated in the handler for its Inserting event. The code for all of this (abridged) looks like this:
Markup:
<asp:GridView ID="gvComplexRates" runat="server" AutoGenerateColumns="False"
DataKeyNames="id" DataSourceID="odsComplexMileageRates"
EnableModelValidation="True" ShowFooter="True">
<Columns>
<asp:TemplateField ShowHeader="False">
:
:
<FooterTemplate>
<asp:LinkButton ID="addLinkButton" runat="server" CausesValidation="false"
CommandName="Insert" Text="Add"></asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
:
:
</asp:GridView>
Code Behind:
Private Sub gvComplexRates_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvComplexRates.RowCommand
Select Case e.CommandName
Case "Insert"
odsComplexMileageRates.Insert()
End Select
End Sub
Private Sub odsComplexMileageRates_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs) Handles odsComplexMileageRates.Inserting
Dim fuelTypeDropDown As DropDownList = gvComplexRates.FooterRow.FindControl("ddFuelTypeInsert")
Dim engineTypeDropDown As DropDownList = gvComplexRates.FooterRow.FindControl("ddEngineTypeInsert")
Dim rateTextBox As TextBox = gvComplexRates.FooterRow.FindControl("tbRateInsert")
Dim vatRateTextBox As TextBox = gvComplexRates.FooterRow.FindControl("tbVatRateInsert")
e.InputParameters("expense_type_id") = ddExpenseTypeSelect.SelectedValue
e.InputParameters("fuel_type_id") = fuelTypeDropDown.SelectedValue
e.InputParameters("engine_type_id") = engineTypeDropDown.SelectedValue
e.InputParameters("rate") = rateTextBox.Text
e.InputParameters("vat_rate") = vatRateTextBox.Text
End Sub
Two of the fields in my FooterRow are DropDownLists that are populated from other tables. Again this works fine and I can add, edit and remove rows without problem.
The problem comes when I use a modal dialog from this page to insert extra rows into the tables used to populate the DropDownLists in the FooterRow. The insert operations work fine and the modal dialog closes and at this point I use a javascript postback (basically a call to __doPostBack()) so that my FooterRow DropDownLists can be updated. The code for this is:
Protected Sub updateFuelEngineDropdowns()
odsFuelTypes.Select()
odsEngineTypes.Select()
Dim dropDown As DropDownList = gvComplexRates.FooterRow.FindControl("ddFuelTypeInsert")
dropDown.DataBind()
dropDown = gvComplexRates.FooterRow.FindControl("ddEngineTypeInsert")
dropDown.DataBind()
End Sub
This sub, updateFuelEngineDropdowns(), is called from the Page Load event. The first time I called it it worked fine. For some reason in subsequent runs through the debugger I'm getting NullReferenceExceptions. Digging into the debug object viewer it is apparent that the GridView FooterRow is referencing the row above the footer which contains no controls (at least not at this non-editing stage) and so, quite reasonably, gives my the Null reference.
The debug QuickView expressions I use are:
gvComplexRates.FooterRow.Controls(3)
DirectCast(gvComplexRates.FooterRow.Controls(3),System.Web.UI.WebControls.DataControlFieldCell).Controls(1)
The first of these shows a tag of td. Which makes sense. The second shows text of "10" which is the content for the row above the footer.
Does anybody know why this is happening?
Thanks Dan
Where are you "providing the missing insert ability"?
You have to rebuild the footer-controls on every postback, the GridView.RowCreated-Event would be a good place.
Update:
You have to Databind your GridView after you inserted new rows into your Dropdowns' Tables.
Right, this is a bit embarrassing. I gave a little white lie in the original question. By omission rather than a deliberate attempt to mislead. I am not, in fact, using a GridView but a subclass of it that will display rows when the datasource contains no data. This enables the user to insert new rows when the table is empty. This subclass overrides the FooterRow property and, to my shame, it was this that was getting things wrong. So I made two errors here: first I failed to test my GridView subclass properly and second I sought to prevent what I thought would be unnecessary attention on my subclass by not showing its use in the code snippets I included in the question. My bad. Thanks to Tim for taking the time to try and help me.
Dan

Inheriting DropDownList and adding custom values using its DataSourceObject

I'm inheriting a DropDownList to add two custom ListItems. The first item is "Select one..." and the second item gets added at the end, it's value is "Custom".
I override DataBind and use the following code:
Dim data As List(Of ListItem) = CType(DataSource, List(Of ListItem))
data.Insert(0, New ListItem("Select one...", SelectOneListItemValue))
If DisplayCustomOption Then
data.Insert(data.Count, New ListItem("Custom", CustomListItemValue))
End If
DataSource = data
MyBase.DataBind()
The problem is this code won't work if the DataSource is anything other than a List of ListItem. Is there a better way of doing this?
You could make the assumption that the data source always inherits IList, in which case you could do the following:
Dim data As IList = CType(DataSource, IList)
data.Insert(0, New ListItem("Select one...", SelectOneListItemValue))
' And so on...
Of course, this assumes that whatever the data source is, it allows you to add objects of the type ListItem. But this might be generic enough for what you need.
You could just leave the databind alone and add your special Items in the DataBound event handler.
Protected Sub MyDropDownList_DataBound(sender As Object, e As EventArgs) _
Handles MyDropDownList.DataBound
MyBase.Items.Insert(0, New ListItem("Select One...", SelectOneListItemValue))
If DisplayCustomOption Then
MyBase.Add(New ListItem("Custom", Custom))
End If
End Sub
(My VB.NET is limited, so you may need to adjust syntax)

DropDownList SelectedIndex value not updating on AutoPostback

It looks like this question was addressed here, but his solution did not work for me. I am creating a dynamic dropdown menu system that populates a secondary dropdownlist with the results of a query based on the selected item in the first dropdown.
First dropdown getting populated:
Dim db As New linqclassesDataContext
Dim categories = (From c In db.faq_cats)
NewFaqDropDownCategory.DataSource = categories
NewFaqDropDownCategory.DataTextField = "category"
NewFaqDropDownCategory.DataValueField = "category_id"
NewFaqDropDownCategory.DataBind()
Unset(categories)
Unset(db)
Second dropdown getting populated:
Protected Sub NewFaqDropDownCategory_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim temp As Integer = CInt(Val(NewFaqDropDownCategory.SelectedIndex))
MsgBox(theDrop.SelectedValue)
Return
'Dim db As New linqclassesDataContext
'Dim faqs = (From f In db.faqs Where f.category = NewFaqDropDownCategory.SelectedValue)
'NewFaqDropDownList.DataSource = faqs
'NewFaqDropDownList.DataTextField = "question"
'NewFaqDropDownList.DataValueField = "id"
'NewFaqDropDownList.DataBind()
'NewFaqLabel.Visible = True
'NewFaqDropDownList.Visible = True
'Unset(faqs)
'Unset(db)
End Sub
The markup for the first dropdown...
<asp:DropDownList ID="NewFaqDropDownCategory" AutoPostBack="true" runat="server" OnSelectedIndexChanged="NewFaqDropDownCategory_SelectedIndexChanged">
</asp:DropDownList>
And the second...
<asp:DropDownList ID="NewFaqDropDownList" runat="server" Visible="false">
</asp:DropDownList>
No matter what I have tried, I always get "1" (the value of the first item in the second dropdown). The post I referenced earlier said this had to do with AutoPostBack and the server not knowing the list was updated yet.
Can anyone clarify this for me a little more?
Set a break point on the line that reads: NewFaqDropDownCategory.DataBind() and one in your event handler (NewFaqDropDownCategory_SelectedIndexChanged).
I suspect the databind is being called right before your NewFaqDropDownCategory_SelectedIndexChanged event fires causing your selected value to change.
If so, you need either to make sure you only databind if you aren't in the middle of your autopostback or instead of using NewFaqDropDownCategory.SelectedIndex on the first line of your event handler you can cast the sender parameter to a DropDownList and use its selected value.
I had the same problem. Found I forgot to look if I was posting back to the page or not and I was binding my DropDownList control in the Page_Load event of the page.
I had forgot to use:
if (!IsPostBack)
{
.... do databind ....
}
I think there is a bug in your LINQ query for the second drop down box
Dim faqs = (From f In db.faqs Where f.category = NewFaqDropDownCategory.SelectedValue)
Here you are comparing SelectedValue to category. Yet in the first combobox you said that the DataValueField should be category_id. Try changing f.category to f.category_id

Resources