Imports System.Drawing
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports System.Data
Imports System.Data.SqlClient


Public Class datagrid2
    Inherits System.Web.UI.Page
    Protected WithEvents MyDataGrid As System.Web.UI.WebControls.DataGrid
    
#Region " Web Forms Designer Generated Code "
    
    'CODEGEN: This procedure is required by the Web Form Designer
    'Do not modify it using the code editor.
    Private Sub InitializeComponent()

    End Sub

#End Region

    Protected Sub Page_Init(ByVal Sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not Page().IsPostBack Then
            BindGrid()
        End If

    End Sub

    Sub BindGrid()
        Dim sqlText As String = "SELECT *  FROM Authors"
        Dim ds As DataSet = GetDataSet(sqlText, "Authors")

        MyDataGrid.DataSource = ds.Tables("Authors").DefaultView
        DataBind()


    End Sub

    Function GetDataSet(ByVal sqlText As String, ByVal dsName As String) As DataSet

        Dim myConnection As New SqlConnection(Application("DBPubsConnectionString").ToString())
        Dim myCommand As New SqlDataAdapter(sqlText, myConnection)

        Dim ds As New DataSet()
        myCommand.Fill(ds, dsName)

        Return ds

    End Function



    Private Sub MyDataGrid_EditCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles MyDataGrid.EditCommand
        MyDataGrid().EditItemIndex = CInt(e.Item.ItemIndex)
        BindGrid()
    End Sub

    Private Sub MyDataGrid_CancelCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles MyDataGrid.CancelCommand
        MyDataGrid().EditItemIndex = -1
        BindGrid()
    End Sub

    Private Sub MyDataGrid_UpdateCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles MyDataGrid.UpdateCommand
        Dim sqlText As String
        Dim au_lname As String
        Dim au_fname As String
        Dim au_id As String

        au_id = e.Item.Cells(1).Text
        au_lname = CType(e.Item.Cells(2).Controls(0), TextBox).Text
        au_fname = CType(e.Item.Cells(3).Controls(0), TextBox).Text

        sqlText = "update authors set au_lname='" & au_lname & "',au_fname='" & au_fname & "' WHERE au_id='" & au_id & "'"
        Dim myConnection As New SqlConnection(Application("DBPubsConnectionString").ToString())
        Dim myCommand As New SqlCommand(sqlText, myConnection)
        myCommand.Connection.Open()
        myCommand.ExecuteNonQuery()
        myCommand.Connection.Close()
        MyDataGrid().EditItemIndex = -1
        BindGrid()

    End Sub
End Class
