I have a gridview which is going to be used to update a mysqldatabase, I only want to update 1 field,
It all works apart from getting the data from the input textbox on the gridview.
in the code below, strdocumentnumber = 77500 I want 77500 to come from the drawing No. column field of the updating row in the gridview and the value that i want to update is strAccess_Code also to come from the gridview Code column.
It all works if hard coding the values.
Private Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating
'' do update..
Dim strdocumentNumber As String = 77500
Dim strAccess_Code As String = 8
dbConn = New MySqlConnection("Data Source=localhost;password=****;user id=root;database=drawlib;")
sql = "UPDATE core " & vbCrLf & _
"SET F6 ='" & strAccess_Code & "'" & vbCrLf & _
"WHERE F1 = '" & strdocumentNumber & "'"
Try
dbConn.Open()
dbcomm = New MySqlCommand(sql, dbConn)
dbread = dbcomm.ExecuteReader()
dbread.Close()
Catch myerror As MySqlException
MsgBox("Error in Saving Data: " & myerror.Message)
'dbread.Close()
Exit Sub
End Try
GridView1.EditIndex = -1
GridView1.DataSource = SqlDataSource2
GridView1.DataBind()
End Sub
thanks
I think you'll have to create a textbox in your codebehind to assign a value from your gridview textbox:
Edit
You may need to find the proper row before pulling the value from the textbox. Try this
Dim row As GridViewRow = GridView1.Rows(e.RowIndex)
If row.RowType = DataControlRowType.DataRow Then
Dim textbox As TextBox = CType(row.FindControl("nameofyourgridview textbox here"),TextBox)
strdocumentNumber = textbox.Text
End If
/Edit
In your Gridview, you'll need to change your BoundField to a TemplateField. See here for an example.
Use the designer to make the conversion (see link above) or select your column in the gridview designer and click the 'convert this column to a templatefield' button. You'll then have a textbox that you can name and grab from the code-behind.
Related
I am dynamically generating a gridview control on the fly. I need to set one of the fields to a hyperlink, and set the value to a dynamic URL. My code so far is:
Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView1.SelectedIndexChanged
Dim strCol As String = GridView1.SelectedRow.Cells(5).Text.ToString
Dim files As String() = IO.Directory.GetFiles(("z:/medadmissions/ap/entering2014/" & strCol & "/"))
Dim strURL As String
Dim HLF As HyperLinkField
Dim dt As New DataTable
dt.Columns.Add("Name")
dt.Columns.Add("Document Type")
For Each f As String In IO.Directory.GetFiles("z:\medadmissions\ap\entering2014\" & strCol & "\")
Dim r As DataRow = dt.NewRow
r("Name") = IO.Path.GetFileName(f)
strURL = "z:\medadmissions\ap\entering2014\" & strCol & "\" & r("Name").ToString
'Want to add this column as a Hyperlink column with strURL
r("Document Type") = "Type"
Next f
Dim gv As New GridView
gvFiles.DataSource = dt
gvFiles.DataBind()
End Sub
I imagine there is an easy way to tell the column labeled "Document Type" that I am wanting it to pass a hyperlink. What am I missing?
Thank you,
David
http://social.msdn.microsoft.com/Forums/windows/en-US/3f53e654-3de3-4a88-8e91-6bcd6bf2d3d1/hyperlink-in-databound-datagridview
go read on that link a bit, you should find something there.
You can also try to put an html encoded string in there. but thats bad practice and I'm still learning these things.
hope this helped
hi what is my problem is in grid view after page loading i am entering some values in text box but after pressing the next page that page values are disappearing..
how can i save and retrieve the values into the grid view ..
i am able to save it in session but how can i past it into the currect page..
here is my code i am able to save it into the values but
after changing other page again entering into the same page how can i past the values into the corresponding page..
Protected Sub Gridview1_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
'Gridview1.PageIndex = e.NewPageIndex
'SetInitialRow()
Dim pageindex As Integer = Gridview1.PageIndex
Response.Write(Gridview1.PageIndex.ToString())
Dim d As Integer = Gridview1.PageCount
Dim texts As String() = New String(Gridview1.PageSize - 1) {}
Dim textBox As TextBox
Dim count As Integer = 0
For Each row As GridViewRow In Gridview1.Rows
textBox = DirectCast(row.FindControl("TextBox1"), TextBox)
If textBox IsNot Nothing Then
texts(count) = textBox.Text
Else
texts(count) = ""
End If
count += 1
Next
Session("one" + "pageindex") = texts
Gridview1.PageIndex= e.NewPageIndex
SetInitialRow()
'Dim sessionint As Integer = Session("page" + "pageindex")
'If Session("page" + "pageindex") IsNot Nothing Then
' Dim textBox1 As TextBox
' Dim texts1 As String() = DirectCast(Session("page" + "pageindex"), String())
' For i As Integer = 0 To Gridview1.Rows.Count - 1
' textBox1 = DirectCast(Gridview1.Rows(i).FindControl("textbox"), TextBox)
' textBox1.Text = texts(i)
' Next
'End If
End Sub
what is your datasource to bind to the gridview ?
These are the 2 ways that I have been doing...
Grab the whole data table and put it into ViewState("dataTable"). Do your filtering of rows and data from there.
Everytime you press 'Next Page', update the rows into the ViewState("dataTable").
Then rebind the gridview with the ViewState("dataTable").
Update the database directly when you press "Next Page".
This code is intended to grab the ID of the deleted record, the user who deleted the record, and the date and time the record was deleted and insert it into a hostical table.
So far, once a record is deleted, the code grabs more than one deleted record.
Please see my code and what I am doing wrong.
Thanks alot in advance for your help.
Protected Sub GridView1_RowDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeletedEventArgs) Handles GridView1.RowDeleted
Dim connStr As String = ConfigurationManager.ConnectionStrings("Constr").ConnectionString
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim sql As String = ""
' Indicate whether the delete operation succeeded.
If e.Exception Is Nothing Then
Dim strID As String = GridView1.FindControl("ID").Cells(1).Text
'Who deleted a record?
sql += "Insert into Archives ([ID],[choice],[date_stamp],[approved],[chcknum],[DeletedBy],[dateDeleted]) "
sql += " SELECT [ID],[choice],[date_stamp],[approved],[chcknum],[login],getDate() from Depends "
sql += " inner join Emp on Depends.employee_id = Emp.employee_id where login ='" & Session.Item("UserName").ToString & "' and upass = '" & Session.Item("Password").ToString & "' and [ID] = '" & strID & "' "
End If
Response.Write(sql)
Response.End()
Try
cnn = New SqlConnection(connStr)
cnn.Open()
cmd = New SqlCommand(sql, cnn)
cmd.ExecuteNonQuery()
cmd.Dispose()
sql = ""
Catch ex As SqlException
Dim errorMsg As String = "Error in Updation"
errorMsg += ex.Message
Throw New Exception(errorMsg)
Finally
cnn.Close()
End Try
End Sub
My problem, I think, lies in this line of code:
Dim strID As String = GridView1.FindControl("ID").Cells(1).Text
I don't think it is correct.
I'm guessing you're looking for the GridView.DataKeys property. Use it to tell your GridView which column(s) in the data is should use as an unique identifer.
You probably also want to look into a few other optimzations for your code:
Use parameters in your query, don't concatenate a SQL statement like that.
Use the Using statement with your SqlConnection and SqlCommand objects for proper and easy disposal.
You're not achiving anything with the try-catch, in fact you're obscuring the exception stack.
Update:
See the GridViewDeletedEventArgs.Keys Property to get the ID of the deleted row. Is the "ID" column part of the query you're using to bind the GridView?
Here's a better (complete) example:
.aspx:
<asp:GridView ID="GridView1" DataKeyNames="ID" AutoGenerateDeleteButton="true" runat="server">
</asp:GridView>
Code-behind, with some dummy data:
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim x() = {New With {.id = 1, .name = "xxx"}, New With {.id = 2, .name = "zzz"}}
GridView1.DataSource = x
GridView1.DataBind()
End If
End Sub
Private Sub GridView1_RowDeleting(sender As Object, e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting
Dim id As Integer = CInt(e.Keys(0))
' Do your stuff!
' Don't forget to rebind the GridView, it will still have the deleted row in Viewstate.
End Sub
End Class
If you are running SQL Server, It might be easier to use a delete trigger on the table.
http://msdn.microsoft.com/en-us/library/aa258254%28v=SQL.80%29.aspx
...deleted and inserted are logical (conceptual) tables. They are structurally similar to the table on which the trigger is defined, that is, the table on which the user action is attempted, and hold the old values or new values of the rows that may be changed by the user action.
I am using ItemTemplate & EditTemplate for editing the gridview. (ASP.net + VB).
I click EDIT button then I can check/uncheck those checkbox and amend the textbox value.
When click UPDATE button, it will fire the RowUpdating Event, But I found that when I get the value for update statement, it still get the value before editing, not updated value.
How can I get the latest & updated value ? Thanks.
Joe
The following is the VB code:
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
'Update the values.
Dim row = Gridview1.Rows(e.RowIndex)
Dim Col1_SL = CType(Gridview1.Rows(e.RowIndex).FindControl("cb1_SL"), CheckBox)
Dim Col1_VL = CType(Gridview1.Rows(e.RowIndex).FindControl("cb1_VL"), CheckBox)
Dim Col1_ML = CType(Gridview1.Rows(e.RowIndex).FindControl("cb1_ML"), CheckBox)
Dim Col1_PH = CType(Gridview1.Rows(e.RowIndex).FindControl("cb1_PH"), CheckBox)
Dim Col1_APH = CType(Gridview1.Rows(e.RowIndex).FindControl("cb1_APH"), CheckBox)
Dim Col1_TOIL = CType(Gridview1.Rows(e.RowIndex).FindControl("cb1_TOIL"), CheckBox)
Dim Col1_Others = CType(Gridview1.Rows(e.RowIndex).FindControl("tb1_Others"), TextBox)
Dim Col1_RosterKey = CType(Gridview1.Rows(e.RowIndex).FindControl("lb1_rosterkey"), Label)
Using conn As New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("hris_shiftdutyConnectionString").ConnectionString)
conn.Open()
cmd.Connection = conn
sql = "SET DATEFORMAT dmy;UPDATE troster SET SL='" & Convert.ToInt32(Col1_SL.Checked) & "' where roster_key='" & Col1_RosterKey.Text & "';"
cmd.CommandText = Sql
reader = cmd.ExecuteReader()
conn.Close()
reader.Close()
End Using
'Reset the edit index.
Gridview1.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub
The most likely reason will be this.
You are calling BindData() on Page_Load without using !IsPostBack
Protected Sub Page_Load Handles Me.Load
If Not IsPostBack
' Bind Grid only at the first load
' Do not load Grid again at Postbacks
BindData()
End If
End Sub
You have 2 options:
There is a separate RowUpdated method that is fired after updates have been performed by the data source that is bound to the grid view. This method will contain the new values for edits and inserts.
The RowUpdating method should have a parameter of type GridViewEventArgs. This will have a property called NewValues that contains the new values. In your example this was the variable e.
Protected Sub GridView1_RowCommand _
(sender As Object, e As GridViewCommandEventArgs) _
Handles GridView1.RowCommand
If e.CommandName.CompareTo("command") = 0 Then
Dim itemID As Integer = Convert.ToInt32( _
GridView1.DataKeys(Convert.ToInt32(e.CommandArgument)).Value)
Dim sqlConn As New SqlConnection("connectionString")
sqlConn.Open()
Dim sqlComm As New SqlCommand("UPDATE itemTable SET property = (property + 1) WHERE id = '" + itemID + "', sqlConn")
sqlComm.ExecuteNonQuery()
sqlConn.Close()
End If
End Sub
Basically, it doesn't work and I don't get it. I've been trying to figure this out for a few days now and I can't see what I've done wrong. As you can see I'm trying to manually update a field in my database with the value of (originalvalue)+1 when the user clicks the buttonfield of the corresponding row.
I guess what I'm asking is if anyone can point out any mistakes, please do, or if there's a better way to do this (without having to go through all the DAL/BLL BS) please tell it to me.
Thank you very much!
I've solved my own problem! Look at the code:
Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
If e.CommandName = "commandname" Then
// Convert the row index stored in the CommandArgument
// property to an Integer.
Dim index = Convert.ToInt32(e.CommandArgument)
// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
Dim row = GridView1.Rows(index)
// Calculate the new value.
Dim tb = CType(row.FindControl("Label1"), Label)
Dim newint As Integer = Convert.ToDouble(tb.Text) + 1
// Get the id of the idea.
Dim id As Integer = Convert.ToInt32( _
GridView1.DataKeys(index).Value)
//Manual update to the database.
Dim con As New SqlConnection("connectionstring")
Dim cmd As New SqlCommand("UPDATE ideatable SET field = " & (newint.ToString) & " WHERE id = " & (id.ToString), con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
//Refresh the page.
Page.Response.Redirect("default.aspx")
End If
End Sub
And remember to set OnRowCommand="GridView1_RowCommand" for the gridview in the aspx file code too, I forgot about that earlier! :/
I'm so happy, thanks for all the help offered! Hope this answer helps someone like me who got stuck.
I think there is problem in your sentence :- Try Below one at place of your Statement
Dim sqlComm As New SqlCommand("UPDATE itemTable SET property = (property + 1) WHERE id = " + itemID + "", sqlConn)
Watch the string you are generating and try to execute it manually and then what happens the table gets UPDATE or not.
Because I Think The "ItemId" is not there in your table.
Try to do This in SQL Server "Select * From itemTable Where id = ItemId" Because i think that the itemId is not there in your table.