Introduction
Let me explain this using a problem I have faced. I am using a database table from where I am getting the Item_id
, Item_name
, Item_price
and Quantity
values. I am populating Item_id
and Item_name
in a drop down list in a key value pair. Here, I am presenting an interface for adding an item to a DataGrid
. Whenever the user presses Add button, I need to check whether that particular item is already present in the DataGrid
or not. If yes, then I have to display a message: "item already present in the list .. do you want to add the quantity". On the basis of user response, I have to perform some action.
Now the main problem is when any body presses Add, I have to go back to the server side for checking the item status, and come back to the client side for displaying the JavaScript message, and user the presses Yes and again the control comes back to the server for adding the item to the DataGrid
.
To solve this problem, I have used JavaScript. Every time when page loads, I am sending a string containing all the item_id
present in the DataGrid
, and when the user presses Add button, I am invoking the JavaScript function which check the selected item_id
in the string. If the item_id
is present, it displays a confirmation message: "item already present in the list .. do you want to add the quantity". If yes, then we need to go back to the server side for adding the quantity, otherwise we'll remain in the client side only. Using this technique, we can save the unnecessary expense of 1 trip to the server.
Screen 1

Screen 2

JavaScript function:
function getCofirmation(inArr)
{
var val= document.form1.DropDownList1.value;
var newarray= inArr.split("/"); var temp;
for(var i= 0; i < newarray.length; i++)
{
temp=newarray[i];
if (temp==val)
{
return window.confirm("Record already Present" +
" do you want to add the quantity ?");
}
}
return false;
}
Server side code:
Dim val As String
Dim retArr As String
Try
Dim dtitems as datatable
dtitems = Cache.Item("dtItems")
Dim ct As Integer = dtitems.Rows.Count
Dim arr(ct) As String
If ct <= 0 Then
btnAddItem.Attributes.Add("OnClick", _
"form1.res.value = getCofirmation(new Array());")
Exit Sub
end if
Dim counter As Int32 = 1
Dim dbrow As DataRow
For Each dbrow In dtitems.Rows
arr(counter) = dbrow("item_id")
counter = counter + 1
Next
retArr=CHR(34)
For counter = 1 To ct
retArr = retArr + arr(counter)
If counter < ct Then
retArr = retArr + "/"
end if
Next
RETARR= RETARR + CHR(34)
Catch e1 As Exception
End Try
Points of Interest
There may be some other better way of doing this thing .. but at that time, I found this best for saving the unnecessary post back time.