I have a gridview in which I insert a checkbox on check_changed even I write the following codes to get the value of Issue Id as mentioned in image also showing values in textbox, but when I use these string in SQL:
Select * from IssueBook Where IssueId IN (values)
It shows error converting varchar to numeric on check_changed I write these codes I have take IssueId (numeric)
Protected Sub CheckBox1_CheckedChanged1(ByVal sender As Object, ByVal e As System.EventArgs)
Dim x As String = ""
For Each row As GridViewRow In GridView1.Rows
Dim cb As CheckBox = row.FindControl("checkbox1")
If cb IsNot Nothing AndAlso cb.Checked Then
If x <> "" Then
x += ","
End If
x += row.Cells(1).Text
End If
Next
RwId.Text = x
Session("SelctdIsuedBokNo") = RwId.Text
In data table I used numeric value.
How can I convert above codes into integers such as 4,5,6, with comma separator?
The IN statement requires a list of comma separated values, not a "string" with those values.
You should create a dynamic SQL and pass it to your Command (SqlCommand or whatever method you are using to execute SQL)... something like: (If you are using SqlClient)
SqlCommand cmd = new SqlCommand(String.Format("Select * from IssueBook Where IssueId IN ({0})", values), your_connection);
Hope it helps.
How about use Convert.ToInt32(); function
http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx
you can use an array :
http://msdn.microsoft.com/en-us/library/vstudio/wak0wfyt.aspx
and convert values into Integer with
Integer.TryParse
http://www.dotnetperls.com/array-vbnet
Try to use
Integer.Parse()
or
Integer.TryParse()
Hope it works.
You can't convert the string "4,5,6" into a single integer value.
Your best bet is to change the select to accept a varchar value.
In this case to avoid sql injection and as long as your IDs (Cells(1).Text values) are integers you should collect your IDs from cells and type safe them in an integer list, then join them with a comma into a string at the end
I've adjusted your code accordingly.
Protected Sub CheckBox1_CheckedChanged1(ByVal sender As Object, ByVal e As System.EventArgs)
Dim Values As List(Of Integer)'your integer list of IDs
For Each row As GridViewRow In GridView1.Rows
Dim cb As CheckBox = row.FindControl("checkbox1")
If cb IsNot Nothing AndAlso cb.Checked Then
Values.Add(Integer.convert(row.Cells(1).Text))'add the ID
End If
Next
RwId.Text = String.Join(",", Values)'pull out the list into a comma delimited string eg "2,45,67,87"
Session("SelctdIsuedBokNo") = RwId.Text
Related
I have the following code...
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As EventArgs) Handles GridView1.RowUpdating
Dim SocioNumInfo As Integer = CInt(GridView1.Rows(GridView1.SelectedIndex).Cells(4).Text)
MsgBox(SocioNumInfo.ToString)
...
End Sub
Now, this code should read the cell, but it gives me the following error:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
The MsgBox is just there for me to check if the data is being read, at the end of the day it should turn that into a parameter so I can add to the DB... but still.. nope nothing. Is that the correct code to read directly from a cell in a choosen row? In the "Protected Sub" area I already tried SelectedIndexChanging and RowEditing, etc... and still nothing. Still throws the error at me.
If I try
Dim SocioNumInfo As String = CStr(GridView1.Rows(GridView1.SelectedRow).Cells(4).Text) it gives me a "cannot be converted to Integer" error.
If no row is selected then GridView1.SelectedIndex is -1. You might have to add a check
If GridView1.SelectedIndex <> -1 Then
' Use GridView1.SelectedIndex here
End If
However, it is easier to access the selected row like this:
Dim row = GridView1.SelectedRow
If Not row Is Nothing AndAlso IsNumeric(row.Cells(2).Text) Then
Dim SocioNumInfo As Integer = CInt(row.Cells(2).Text)
....
End If
Note that the cell index is zero based. row.Cells(4) is in the 5th column.
I have an unbound Gridview that is populated by a Linq to Entities query and would like to convert string values in a particular column to lowercase.
In the Gridview's RowDataBound event, i have tried StrConv(e.Row.Cells(3).Text, VbStrConv.ProperCase) but this doesn't work.
I have also tried StrConv(emp.Name, VbStrConv.ProperCase) in the LiNQ to Entities query but still the Name values returned are to converted to Lower-case.
Protected Sub GridView3_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView3.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
For i As Integer = 0 To e.Row.Cells.Count - 1
Dim cellDate As Date
If Date.TryParse(e.Row.Cells(i).Text, cellDate) Then
e.Row.Cells(i).Text = String.Format("{0:d}", cellDate)
End If
Next
End If
StrConv(e.Row.Cells(4).Text, VbStrConv.ProperCase)
End Sub
As far as I can see, strConv returns a string, which should be used, I think like:
e.Row.Cells(4).Text = StrConv(e.Row.Cells(4).Text, VbStrConv.ProperCase)
have you tried to do this:
string strLower = e.Row.Cells[0].Text.ToLower();
and then use the strLower as the lower case string.
I am using the method described in the following LINK and I am using the following code to encrypt:
'Page1.aspx
Protected Sub butEncrypt_Click(sender As Object, e As EventArgs) Handles butEncrypt.Click
Dim QueryString As String = "type=Int&pk=" & _primaryKey
QueryString = Tools.encryptQueryString(QueryString)
Response.Redirect(/SearchResults.aspx?Val=" & QueryString)
End Sub
and then finally de-encrypt:
'SearchResults.aspx
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Not IsPostBack) Then
If Not String.IsNullOrEmpty(HttpContext.Current.Request(CIAppGlobals.GlobalVar.Val)) Then
Dim qs As String = Request.QueryString(CIAppGlobals.GlobalVar.Val)
qs = Tools.decryptQueryString(qs)
Dim Values As String() = qs.Split(CChar("&"))
_imageType = String.Empty
_primaryKey = 0
For Each value As String In Values
Dim data As String() = value.Split(CChar("="))
Select Case data(0).ToUpper
Case "TYPE"
_imageType = data(1)
Case "PK"
_primaryKey = CInt(data(1))
End Select
Next
Else
_imageType = HttpContext.Current.Request("type")
_primaryKey = CInt(HttpContext.Current.Request("pk"))
End If
End If
End Sub
My question is should I being using a different method to extract the decoded query string values other than what I am doing? Thanks in advance for your constructive responses.
Solution
After looking at Darin's response I have decided to incorporate it into my project, here is my updated code:
'Page1.aspx
Protected Sub butEncrypt_Click(sender As Object, e As EventArgs) Handles butEncrypt.Click
Dim query = HttpUtility.ParseQueryString(String.Empty)
query("type") = "Int"
query("pk") = CStr(_primaryKey)
Dim QueryString As String = Tools.encryptQueryString(query.ToString())
Response.Redirect(/SearchResults.aspx?Val=" & QueryString)
End Sub
I still want to encrypt the query string because I want to prevent users from changing the Query String Values manually
You are incorrectly building the query string in the first place. You are using string concatenations and not properly encoding them. What if _primaryKey contains a & or = characters? You could use the ParseQueryString method to properly build a query string:
Dim query = HttpUtility.ParseQueryString(String.Empty)
query("type") = "Int"
query("pk") = _primaryKey
Dim queryString = query.ToString()
The same method could be used for parsing the decoded query string:
Dim values = HttpUtility.ParseQueryString(qs)
Dim type = query("type")
Dim primaryKey = query("pk")
' work with the type and primaryKey values
Never use string concatenations and splitting when dealing with urls. Always use the right tool for the right job.
That's as far as creating/parsing query strings is concerned. As far as encrypting/decryption the values is concerned, you haven't shown/told us anything about the Tools class that you are using so I cannot provide you with any constructive comments about it.
You know that the best encryption is to never send the actual value to the client. So you could store it in some backend storage on the server and then use an unique id in the url. This id could be used on the target page to fetch the original value. This way you don't need to be encrypting/decrypting anything.
I need to compare two string and get both duplicate and original value .
On calling chkDuplicateValue function i need to get both duplicate and original in the return value ?
, acts as delimeter for both the string .
Dim oldStr As String = "test1,test2,test"
Dim newStr As String = "test,test53"
Example out put : Original Value :test1,test2,test,test53 duplicate Value : test
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim oldStr As String = "test1,test2,test"
Dim newStr As String = "test,test53"
Dim refinedString As String = chkDuplicateValue(newStr, oldStr)
'On calling this function i need to get both duplicate and original in the return value ?
Response.Write("Original Value" & refinedString(0))
Response.Write("duplicate Value" & refinedString(1))
'Example out put : Original Value :test1,test2,test,test53 duplicate Value : test
End Sub
Function chkDuplicateValue(ByVal newStr As String, ByVal oldStr As String) As String
Dim duplicate As String = ""
End Function
return oldStr.Split(',').Union(newStr.Spit(','));
and if that doesn't work using the Join linq extension method
Use Linq Intersect to return duplicates and Union to return Distinctlist. Pass newStr ByRef, so, that unduplicated string will be returned on newStr. Also, remeber to reference System.Linq
Function chkDuplicateValue(ByRef newStr As String, ByVal oldStr As String) As String
Dim duplicate As String = ""
duplicate = String.Join(",",(newStr.Split(',').Intersect(oldStr.Split(','))).ToArray())
newStr = String.Join(",",(newStr.Split(',').Union(oldStr.Split(','))).ToArray())
return uplicate
End Function
I am trying to loop through the rows of my gridview and retrieve the data key value of each row and then execute some code to run sql queries. How can I get the data key value of each row in variable? right now I am receiving an error message saying:
value of type system.web.ui.webcontrols.datakey cannot be converted to integer.
Here is my code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
For Each row As GridViewRow In GridView1.Rows
Dim therowindex As Integer = row.RowIndex
Dim theid As Integer = GridView1.DataKeys([therowindex])
'execute some more code running queries using the data key value.
Next
End Sub
You can iterate through the .Rows collection, and then find the row's DataKey value.
foreach(GridViewRow row in GridView1.Rows)
{
string theDataKey = GridView1.DataKeys[row.RowIndex].Value.ToString();
// Do something with your index/key value
}
You have to use Value property.
Dim theid As Integer = Integer.Parse(GridView1.DataKeys(therowindex).Value.ToString())