I have a SQL Server table with 5 columns. col1 is the primary key. I an working in ASP.net 4.0.
I want to be able to edit and update my SQL Server table with the edit and update respectively.
I am having a little trouble with the update. Here is my code:
<asp:GridView ID="GridView1" runat="server" AutoPostBack="True" AutoGenerateColumns="True" AutoGenerateEditButton="True" OnRowEditing="Gridview1_OnRowEditing" OnRowUpdating="GridView1_OnRowUpdating">
</asp:GridView>
Code:
Sub ShowGrid()
Dim connStr, cmdStr As String
connStr = "connection string works"
cmdStr = "SELECT * FROM table1;"
Dim MyDataSet As New DataSet
Dim MyDataTable As New DataTable()
Try
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(cmdStr, conn)
conn.Open()
cmd.ExecuteNonQuery()
Using MyDataAdaptor As New SqlDataAdapter(cmd)
MyDataAdaptor.Fill(MyDataSet)
MyDataTable = MyDataSet.Tables(0)
GridView1.EditIndex = Convert.ToInt32(ViewState("edit"))
GridView1.DataSource = MyDataTable
GridView1.DataBind()
End Using
conn.Close()
cmd.Dispose()
conn.Dispose()
End Using
End Using
Catch ex As Exception
Throw ex
End Try
End Sub
Protected Sub GridView1_OnRowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
ViewState("edit") = GridView1.EditIndex
ShowGrid()
End Sub
Protected Sub GridView1_OnRowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
Dim connStr, cmdStr As String
connStr = "connection string works"
cmdStr = "UPDATE table1 SET (col2=#col2,col3=#col3,col4=#col4,col5=#col5) WHERE col1=#col1;"
Try
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(cmdStr, conn)
conn.Open()
cmd.Parameters.AddWithValue("#col1", GridView1.Rows(e.RowIndex).Cells(0).Text)
cmd.Parameters.AddWithValue("#col2", GridView1.Rows(e.RowIndex).Cells(1).Text)
cmd.Parameters.AddWithValue("#col3", GridView1.Rows(e.RowIndex).Cells(2).Text)
cmd.Parameters.AddWithValue("#col4", GridView1.Rows(e.RowIndex).Cells(3).Text)
cmd.Parameters.AddWithValue("#col5", GridView1.Rows(e.RowIndex).Cells(4).Text)
cmd.ExecuteNonQuery()
conn.Close()
cmd.Dispose()
conn.Dispose()
End Using
End Using
Catch ex As Exception
End Try
ViewState("edit") = e.RowIndex
ShowGrid()
End Sub
Related
I have a web form to save transactions in database and a button to display the previous action but it doesn't work although there is no error message.
Protected Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim nmb As Long = Convert.ToInt32(TextBox1.Text) - 1
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("dataConnectionString").ConnectionString)
Dim sql1 As New SqlCommand("select * from internal_trans where numbr = #numbr", conn)
sql1.Parameters.AddWithValue("#numbr", nmb)
conn.Open()
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
adapter.SelectCommand = sql1
adapter.Fill(ds)
Me.TextBox1.Text = ds.Tables(0).Rows(0).Item(0).ToString
Me.TextBox2.Text = ds.Tables(0).Rows(0).Item(1).ToString
adapter.Dispose()
sql1.Dispose()
conn.Close()
End Sub
I am having trouble with OnRowUpdating event. It will not save the new data in the GridView1.EditIndex row. It just reverts back to the old value as soon as you press Update.
The OnRowEditing seems to be functioning correctly.
The same goes for OnRowCancelingEdit it seems to be functioning correctly.
ASPX:
<asp:GridView ID="GridView1" runat="server" AllowSorting="true" AutoPostBack="True" AutoGenerateColumns="True" AutoGenerateEditButton="True" OnRowCancelingEdit="Gridview1_OnRowCancelingEdit" OnRowEditing="Gridview1_OnRowEditing" OnRowUpdating="GridView1_OnRowUpdating"
AllowPaging="True" PageSize="50" OnPageIndexChanging="GridView1_PageIndexChanging">
</asp:GridView>
Code behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ViewState("pageIndex") = 1
ViewState("edit") = -1
ShowGrid()
End Sub
Sub ShowGrid()
Dim connStr, cmdStr As String
connStr = connection string works"
cmdStr = "SELECT * FROM OrbitDates;"
Dim ds As New DataSet
Dim dt As New DataTable()
Try
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(cmdStr, conn)
conn.Open()
cmd.ExecuteNonQuery()
Using da As New SqlDataAdapter(cmd)
da.Fill(ds)
dt = ds.Tables(0)
GridView1.EditIndex = Convert.ToInt32(ViewState("edit"))
dt.DefaultView.Sort = ViewState("Sort")
GridView1.DataSource = dt.DefaultView
GridView1.DataBind()
GridView1.PageIndex = Convert.ToInt32(ViewState("pageIndex"))
End Using
conn.Close()
cmd.Dispose()
conn.Dispose()
End Using
End Using
Catch ex As Exception
End Try
End Sub
Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs) Handles GridView1.PageIndexChanging
GridView1.PageIndex = e.NewPageIndex
ViewState("pageIndex") = e.NewPageIndex.ToString()
ShowGrid()
End Sub
Protected Sub GridView1_OnRowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
ViewState("edit") = GridView1.EditIndex
ShowGrid()
End Sub
Protected Sub GridView1_OnRowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
GridView1.EditIndex = -1
ViewState("edit") = GridView1.EditIndex
ShowGrid()
End Sub
Protected Sub GridView1_OnRowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
Dim connStr, cmdStr As String
connStr = "connection string works"
cmdStr = "UPDATE OrbitDates SET (JD=#JD,Xecl1=#Xecl1,Yecl1=#Yecl1,Zecl1=#Zecl1) WHERE ido=#ido;"
Try
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(cmdStr, conn)
conn.Open()
cmd.Parameters.AddWithValue("#ido", GridView1.Rows(e.RowIndex).Cells(0).Text)
cmd.Parameters.AddWithValue("#JD", GridView1.Rows(e.RowIndex).Cells(1).Text)
cmd.Parameters.AddWithValue("#Xecl1", GridView1.Rows(e.RowIndex).Cells(2).Text)
cmd.Parameters.AddWithValue("#Yecl1", GridView1.Rows(e.RowIndex).Cells(3).Text)
cmd.Parameters.AddWithValue("#Zecl1", GridView1.Rows(e.RowIndex).Cells(4).Text)
cmd.ExecuteNonQuery()
conn.Close()
cmd.Dispose()
conn.Dispose()
End Using
End Using
Catch ex As Exception
Throw ex
End Try
ViewState("edit") = e.RowIndex
ShowGrid()
End Sub
The problem is the GridView is overwritten with the old data before executing GridView1_OnRowUpdating because of this code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ViewState("pageIndex") = 1
ViewState("edit") = -1
ShowGrid()
End Sub
You need to put If Not IsPostBack inside Page_Load:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
ViewState("pageIndex") = 1
ViewState("edit") = -1
ShowGrid()
End If
End Sub
Try to understand more about ASP.NET Page Life Cycle.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ViewState("pageIndex") = 1
ViewState("edit") = -1
ShowGrid()
End Sub
Sub ShowGrid()
Dim connStr, cmdStr As String
connStr = connection string works"
cmdStr = "SELECT * FROM OrbitDates;"
Dim ds As New DataSet
Dim dt As New DataTable()
Try
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(cmdStr, conn)
conn.Open()
cmd.ExecuteNonQuery()
Using da As New SqlDataAdapter(cmd)
da.Fill(ds)
dt = ds.Tables(0)
GridView1.EditIndex = Convert.ToInt32(ViewState("edit"))
dt.DefaultView.Sort = ViewState("Sort")
GridView1.DataSource = dt.DefaultView
GridView1.DataBind()
GridView1.PageIndex = Convert.ToInt32(ViewState("pageIndex"))
End Using
conn.Close()
cmd.Dispose()
conn.Dispose()
End Using
End Using
Catch ex As Exception
End Try
End Sub
Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs) Handles GridView1.PageIndexChanging
GridView1.PageIndex = e.NewPageIndex
ViewState("pageIndex") = e.NewPageIndex.ToString()
ShowGrid()
End Sub
Protected Sub GridView1_OnRowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
ViewState("edit") = GridView1.EditIndex
ShowGrid()
End Sub
Protected Sub GridView1_OnRowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
GridView1.EditIndex = -1
ViewState("edit") = GridView1.EditIndex
ShowGrid()
End Sub
Protected Sub GridView1_OnRowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
Dim connStr, cmdStr As String
connStr = "connection string works"
cmdStr = "UPDATE OrbitDates SET (JD=#JD,Xecl1=#Xecl1,Yecl1=#Yecl1,Zecl1=#Zecl1) WHERE ido=#ido;"
Try
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(cmdStr, conn)
conn.Open()
cmd.Parameters.AddWithValue("#ido", GridView1.Rows(e.RowIndex).Cells(0).Text)
cmd.Parameters.AddWithValue("#JD", GridView1.Rows(e.RowIndex).Cells(1).Text)
cmd.Parameters.AddWithValue("#Xecl1", GridView1.Rows(e.RowIndex).Cells(2).Text)
cmd.Parameters.AddWithValue("#Yecl1", GridView1.Rows(e.RowIndex).Cells(3).Text)
cmd.Parameters.AddWithValue("#Zecl1", GridView1.Rows(e.RowIndex).Cells(4).Text)
cmd.ExecuteNonQuery()
conn.Close()
cmd.Dispose()
conn.Dispose()
End Using
End Using
Catch ex As Exception
Throw ex
End Try
ViewState("edit") = e.RowIndex
ShowGrid()
End Sub
I'm trying to download a file from an SQL Server table. I am using a GridView. Whenever I try to download a file, I get a corrupted file.
I am using ASP.NET and VB.NET with SQL Server 2012 Express.
Any ideas why ?
Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView1.SelectedIndexChanged
Dim ContentID = Convert.ToInt32(GridView1.SelectedRow.Cells(1).Text)
Dim ContentName = GridView1.SelectedRow.Cells(2).Text
Dim ContentType = GridView1.SelectedRow.Cells(3).Text
lblContentName.Text = "[ " + ContentName + " ]"
lblContentName.Visible = True
End Sub
Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
Dim cn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True;")
If e.CommandName = "Download" Then
Dim filename As String = String.Empty
Dim id As Integer = Convert.ToInt32(e.CommandArgument)
Dim cmd As New SqlCommand("SELECT content_name,content_type,content_data FROM content WHERE content_id = " & id, cn)
cn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader
Dim bytes As Byte()
dr = cmd.ExecuteReader()
If dr.Read() Then
filename = dr("content_name").ToString()
Response.ContentType = dr("content_type").ToString()
Response.AddHeader("Content-Disposition", "attachment;filename=" & filename)
bytes = DirectCast(dr("content_file"), Byte())
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.BinaryWrite(bytes)
Response.Flush()
Response.[End]()
End If
End If
End Sub
Private Sub BindGrid()
Dim constr As String = ConfigurationManager.ConnectionStrings("ConnStringDb1").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand()
cmd.CommandText = "SELECT content_id, content_name FROM content"
cmd.Connection = con
con.Open()
GridView1.DataSource = cmd.ExecuteReader()
GridView1.DataBind()
con.Close()
End Using
End Using
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGrid()
End If
End Sub
What is the problem in my this code?
The code is working fine but when i enter new record in table and refresh the page then the changes will not be reflected...
what was the problem iam confused..
Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
Dim ds As New DataSet()
Dim connStr As String = "Data Source=DOBRIYAL-PC;Initial Catalog=MenuDb;Integrated Security=True"
Using conn As New SqlConnection(connStr)
Dim sql As String = "Select MenuID, Text, Description, ParentID from Menu"
Dim da As New SqlDataAdapter(sql, conn)
da.Fill(ds)
da.Dispose()
da.AcceptChangesDuringFill = True
End Using
ds.DataSetName = "Menus"
ds.Tables(0).TableName = "Menu"
ds.GetChanges()
Dim relation As New DataRelation("ParentChild", ds.Tables("Menu").Columns("MenuID"), ds.Tables("Menu").Columns("ParentID"), True)
relation.Nested = True
ds.Relations.Add(relation)
XmlDataSource1.Data = ds.GetXml()
If Request.Params("Sel") IsNot Nothing Then
Page.Controls.Add(New System.Web.UI.LiteralControl("You selected " + Request.Params("Sel")))
End If
XmlDataSource1.DataBind()
RadMenu1.DataBind()
End Sub
I have refatored your source code now you should see your new records on page load
Private Sub BindData()
Dim ds As New DataSet()
Dim connStr As String = "Data Source=DOBRIYAL-PC;Initial Catalog=MenuDb;Integrated Security=True"
Using conn As New SqlConnection(connStr)
Dim sql As String = "Select MenuID, Text, Description, ParentID from Menu"
Dim da As New SqlDataAdapter(sql, conn)
da.Fill(ds)
da.Dispose()
da.AcceptChangesDuringFill = True
End Using
ds.DataSetName = "Menus"
ds.Tables(0).TableName = "Menu"
ds.GetChanges()
Dim relation As New DataRelation("ParentChild", ds.Tables("Menu").Columns("MenuID"), ds.Tables("Menu").Columns("ParentID"), True)
relation.Nested = True
ds.Relations.Add(relation)
XmlDataSource1.Data = ds.GetXml()
If Request.Params("Sel") IsNot Nothing Then
Page.Controls.Add(New System.Web.UI.LiteralControl("You selected " + Request.Params("Sel")))
End If
XmlDataSource1.DataBind()
RadMenu1.DataBind()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.BindData()
End Sub
I am trying to execute a stored procedure and place the information in a datagrid(without using the .net wizard) i want to do it manually. Using ado.net i believe. I am using vb.net and asp.net
Public cmd As New SqlCommand()
Public saoda As New SqlDataAdapter(cmd)
Public conn As New SqlConnection(" ")
Dim saods As New DataSet
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim reader As SqlDataReader
cmd.Parameters.AddWithValue("#yeartoget", DropDownList1.SelectedValue)
cmd.CommandText = "casof"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = conn
conn.Open()
reader = cmd.ExecuteReader()
' Data is accessible through the DataReader object here.
GridView1.DataSource = saods
saoda.FillSchema(saods, SchemaType.Mapped)
GridView1.DataBind()
conn.Close()
End Sub
End Class
vvvvv
Dim pctofsales As New DataColumn
pctofsales = New DataColumn("PCTofsales", GetType(Decimal))
pctofsales.Expression = "IIF([YEsales] = 0, 0, [ASOFSales] / [YEsales])"
saods1.Tables("salesasoftable").Columns.Add(pctofsales)
You don't need to bind a DataSet to a GridView - a SqlDataReader will suffice. That is, you could use the following:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim reader As SqlDataReader
cmd.Parameters.AddWithValue("#yeartoget", DropDownList1.SelectedValue)
cmd.CommandText = "casof"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = conn
conn.Open()
reader = cmd.ExecuteReader()
GridView1.DataSource = reader
GridView1.DataBind()
conn.Close()
End Sub
However, if you want/need to use a DataTable, that's no big deal, either. The following snippet loads a reader into a DataTable:
Dim reader As SqlDataReader
cmd.Parameters.AddWithValue("#yeartoget", DropDownList1.SelectedValue)
cmd.CommandText = "casof"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = conn
conn.Open()
reader = cmd.ExecuteReader()
Dim myTable As DataTable = New DataTable()
myTable.Load(reader)
GridView1.DataSource = dt
GridView1.DataBind()
conn.Close()
Happy Programming!