Replace detailview field before insert - asp.net

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...

Related

validate a template text box with database value

I'm developing a website and have a textbox in gridview template field. This textbox collects the input for the "order quantity" which has to be compared against the "available quantity"(stored in the database).
I use RowEditing, RowUpdating and RowCanceling events for edit operations in gridview.
I tried implementing the above requirement with "TextChanged" Event of text box. But the issue is, when the user edits the quantity and clicks on "Update" button, text box event fires first and update button event doesn't fire. So, user is forced to click the "Update" button again.
Is there any work around for the above scenario or any other event used to implement above requirement?
Thanks,
Balaji g
You can Use RangeValidator For That...
<asp:RangeValidator ID="RangeValidator1" ControlToValidate="YourTexBoxId"
runat="server" MinimumValue="0" Type="Integer"
MaximumValue='<%# GetQuantity(Eval(TotalQaunt).ToString(),Eval(ItemId).ToString()) %>'
ErrorMessage="RangeValidator"></asp:RangeValidator>
write a function lyk this ON CODE BEHIND
string GetQuantity(string totalquantity,string itemid)
{
DO OPERATRION TO GET QUANTITY.....
return quantity;
}
I think I'd try the CustomValidator. With the CustomValidator, you can define the validation code in the "_ServerValidate" event handler.
In your validation code, you can call the database to get the current value and then compare it to the submitted value (which would be available via the event handler's ServerValidateEventArgs paramenter if you specify a ControlToValidate).
In order to look up the current value in the database, you'll need to know which record was clicked. For that, you could either use the row button's CommandArgument property or include a hidden field in your row to store some type of ID. Then you could capture that ID and use it to look up the desired record in the database.
Updated with Code
Protected Sub cusCustom_ServerValidate(source As Object, args As System.Web.UI.WebControls.ServerValidateEventArgs)
Dim cv As CustomValidator = CType(source, CustomValidator)
Dim HiddenField_ID As HiddenField = CType(cv.Parent.FindControl("HiddenField_ID"), HiddenField)
*** Use ID to look up value in database ***
End Sub

RangeValidator not working when selecting DropDownList value using jQuery

I inherited a site which I am in the middle of updating which has a DropDownList and a RangeValidator assigned to it. The data is bound to the dropdown on Page_Load. The values are retrieved from the database so the value property of each item is set to the unique ID of the item in the DB.
The RangeValidator looks something like:
<asp:rangevalidator id="ddRangeValidator" runat="server" ControlToValidate="ddMenu" ErrorMessage="Please select value in range" MinimumValue="1" MaximumValue="100000" Type="Integer">*</asp:rangevalidator>
I have a method which automatically populates this value in jQuery e.g.
$("#ddMenu").val("An Option");
This works, however, when I try to post the page the range validation fails. Then even if I manually select that value, or select another valid value it still won't validate. The only way to make it validate is to select non-valid value and then re-selecting a valid one.
Any ideas?
Update
Here is the data binding code:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load, Me.Load
If Not Page.IsPostBack Then
Dim ds As New DataSet()
Dim myDbObject As New myDbObject()
ds = myDbObject.ToDataSet() // retrieves all objects from the database
// store the results in a temporary view to filter
Dim dv As DataView
dv = New DataView(ds.Tables(0), "IsLive = True", "ID", DataViewRowState.CurrentRows)
Dim i As Integer = 0
ddMenu.Items.Add("Select a value")
ddMenu.Items.Item(0).Value = 0
// add all objects from filtered list into drop down menu
For i = 0 To dv.Count - 1
With ddMenu.Items
// add a new item
.Add(dv.Item(i).Item("Name"))
// set the Value property as unique ID of object
.Item(i + 1).Value = dv.Item(i).Item("ID")
End With
Next
End If
End If
Turns out it was an issue with my page loading twice...so now the issue is going to be tracking down why it is loading twice!
I guess the Range validator verifies the actual "value" of the dropdown list. May it be possible that by using jQuery to populate your dropdown the actual entry doesn't get a proper option "value"? Could you maybe post the rendered HTML code of your dropdown list?

How do I get the EntityDataSource to allow me to access child entities?

I have a very simple mockup I'm making for a client that uses the Northwind database. I have an EDMX file with three entities: Products, Categories, and Suppliers.
I'm trying to create a page that has a GridView that shows the products, including the category name and supplier name. With LINQ to SQL I can have the LinqDataSource control return the Products entity and then can have a TemplateField in the GridView like so:
<ItemTemplate>
<%# Eval("Category.CategoryName") %>
</ItemTemplate>
However, it seems the EntityDataSource is not playing so nicely. It's as if it won't lazy load the category data. I have a very simple EDS:
<asp:EntityDataSource ID="dsProducts" runat="server"
ConnectionString="name=NorthwindEntities"
DefaultContainerName="NorthwindEntities" EnableFlattening="False"
EntitySetName="Products">
</asp:EntityDataSource>
But the GridView does not show the category name. If I create a RowDataBound event handler for the GridView and get the Product entity being bound to the row, I see that the product's Category property returns Nothing. For example, if I do:
Protected Sub gvProducts_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvProducts.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim p As NorthwindModel.Product = e.Row.DataItem
Dim catName = p.Category.CategoryName
End If
End Sub
I get a NullReferenceException when trying to do p.Category.CategoryName.
However, I know lazy loading works for the EDMX b/c if I write code in the Page_Load event handler like:
Dim context As New NorthwindModel.NorthwindEntities
Dim p = context.Products.Take(1).Single()
I can get the Category name via p.Category.CategoryName without error.
Is there some voodoo I need to do to get the EntityDataSource to include support for retrieving related entities?
Thanks
SOLUTION:
I specified the Include property of the EntityDataSource, noting the entity objects to include. Specifically, I updated my EntityDataSource control's declarative markup to:
<asp:EntityDataSource ID="dsProducts" runat="server"
ConnectionString="name=NorthwindEntities"
DefaultContainerName="NorthwindEntities" EnableFlattening="False"
EntitySetName="Products" Include="Category,Supplier">
</asp:EntityDataSource>
You need to use the Include property of the entity data source to get related entities. Then, change the markup to query into these entities.
Take a look a a couple of pages from the book "Programming Entity Framework": http://books.google.com/books?id=wp8V0vBebnoC&pg=PA284&lpg=PA284&dq=entitydatasource+include&source=bl&ots=cKtfB1J8vC&sig=C--WGKuU-9CNOQgDxdN0MpSMLt4&hl=en&ei=OidPTMnKB5P-ngeM1rinBw&sa=X&oi=book_result&ct=result&resnum=7&ved=0CDAQ6AEwBg#v=onepage&q=entitydatasource%20include&f=false

Getting information (on click) that was used to programatically generate asp controls

How may one get information that was used to programatically generate asp controls?
For example, I pulled a DataTable of user objects from the database and have organized them on a page, listing groupings such as a list of employees directly under the employer for each employer. On the page, I list each user's Username as a LinkButton. When I click one of these employees, I want to redirect the page (which is easy) and set a session variable to the selected user's UserId (which seems not so easy). How can I pull this UserId value back? These elements are not hard-coded with nice names (as they are generated in a for each loop).
Code from comment below:
Dim lnkbtnPm As New LinkButton ' is my link button. '
lnkbtnPm.Text = pmDr.Item("Username") ' where pmDr is my datarow. '
lnkbtnPm.CommandArgument = pmDr.Item("UserId")
lnkbtnPm.CommandName = "CommandNameHere"
panelToAddControlTo.Controls.Add(lnkbtnPm)
Thanks :)
I think this is what you would use the CommandName and CommandArgument properties of the LinkButton for. Assign the user id as CommandArgument and a suitable string as CommandName and hook up the Command event to an event handler:
Sub LinkButton_Command(sender As Object, e As CommandEventArgs)
' e.CommandArgument will contain the user id '
End Sub
Update
The problem is that the event handler is never attached. Use AddHandler to do that:
Dim lnkbtnPm As New LinkButton
lnkbtnPm.Text = pmDr.Item("Username") ' where pmDr is my datarow. '
lnkbtnPm.CommandArgument = pmDr.Item("UserId")
lnkbtnPm.CommandName = "CommandNameHere"
AddHandler lnkbtnPm.Command, AddressOf LinkButton_Command
panelToAddControlTo.Controls.Add(lnkbtnPm)

GridView Row to Object Type

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.

Resources