Datagrid med autonr som key. problem at hente datakey fra grid
Hej...Jeg har taget en template fra web-Matrix som hedder "Editable Datagrid" også lavet de ændringer som der står skrivet og en lille smule mere. Min nøgle i databasen er et autogenereret tal, men jeg kan ikke få hentet dette tal ud af datagrid'et når jeg bruger "update" og "delete". fejlen den 'kaster':
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index.
Her er hele min kode: (linien med = linie over og under er der fejlen forkommer)
<%@ Page Language="VB" %>
<%@ import Namespace="System.data" %>
<%@ import Namespace="System.data.oleDB" %>
<%@ import Namespace="System.Configuration" %>
<script runat="server">
' Src="default.aspx.vb" Inherits="defaultaspx"
' TODO: update the ConnectionString and Command values for your application
Dim appsettings As NameValueCollection = ConfigurationSettings.AppSettings
Dim ConnectionString As String = appsettings("dns") & Server.MapPath(appsettings("sti"))
Dim SelectCommand As String = "SELECT id, item_1, item_2, item_3 FROM liste"
Dim isEditing As Boolean = False
Public Sub Page_Load(Sender As Object, E As EventArgs)
If Not Page.IsPostBack Then
' Databind the data grid on the first request only
' (on postback, bind only in editing, paging and sorting commands)
BindGrid()
End If
End Sub
' ---------------------------------------------------------------
'
' DataGrid Commands: Page, Sort, Edit, Update, Cancel, Delete
'
Public Sub DataGrid_ItemCommand(Sender As Object, E As DataGridCommandEventArgs)
' this event fires prior to all of the other commands
' use it to provide a more graceful transition out of edit mode
CheckIsEditing(e.CommandName)
End Sub
Public Sub CheckIsEditing(commandName As String)
If DataGrid1.EditItemIndex <> -1 Then
' we are currently editing a row
If commandName <> "Cancel" And commandName <> "Update" Then
' user's edit changes (If any) will not be committed
Message.Text = "Your changes have not been saved yet. Please press update to save your changes, or cancel to discard your changes, before selecting another item."
isEditing = True
End If
End If
End Sub
Public Sub DataGrid_Edit(Sender As Object, E As DataGridCommandEventArgs)
' turn on editing for the selected row
If Not isEditing Then
DataGrid1.EditItemIndex = e.Item.ItemIndex
BindGrid()
End If
End Sub
Public Sub DataGrid_Update(Sender As Object, E As DataGridCommandEventArgs)
' update the database with the new values
' TODO: update the Command value for your application
Dim myConnection As New OleDbConnection(ConnectionString)
Dim UpdateCommand As OleDbCommand = new OleDbCommand()
UpdateCommand.Connection = myConnection
If AddingNew = True Then
UpdateCommand.CommandText = "INSERT INTO liste(item_1, item_2, item_3) VALUES (@item_1, @item_2, @item_3)"
Else
UpdateCommand.CommandText = "UPDATE liste SET item_1 = @item_1, item_2 = @item_2, item_3 = @item_3 WHERE id = @id"
================================================
Dim keyValue As Integer = Cint(DataGrid1.DataKeys(e.Item.ItemIndex))
================================================
UpdateCommand.Parameters.Add("@id", OleDbType.Integer).Value = keyValue
End If
' get and add the edit values to the command
UpdateCommand.Parameters.Add("@item_1", OleDbType.VarChar, 50).Value = CType(e.Item.Cells(1).Controls(0), TextBox).Text
UpdateCommand.Parameters.Add("@item_2", OleDbType.VarChar, 50).Value = CType(e.Item.Cells(2).Controls(0), TextBox).Text
UpdateCommand.Parameters.Add("@item_3", OleDbType.Boolean).Value = CType(e.Item.Cells(3).Controls(0), TextBox).Text
' execute the command
Try
myConnection.Open()
UpdateCommand.ExecuteNonQuery()
Catch ex as Exception
Message.Text = ex.ToString()
Finally
myConnection.Close()
End Try
' Resort the grid for new records
If AddingNew = True Then
DataGrid1.CurrentPageIndex = 0
AddingNew = false
End If
' rebind the grid
DataGrid1.EditItemIndex = -1
BindGrid()
End Sub
Public Sub DataGrid_Cancel(Sender As Object, E As DataGridCommandEventArgs)
' cancel editing
DataGrid1.EditItemIndex = -1
BindGrid()
AddingNew = False
End Sub
Public Sub DataGrid_Delete(Sender As Object, E As DataGridCommandEventArgs)
' delete the selected row
If Not isEditing Then
' the key value for this row is in the DataKeys collection
================================================
Dim keyValue As Integer = Cint(DataGrid1.DataKeys(e.Item.ItemIndex))
================================================
' TODO: update the Command value for your application
Dim myConnection As New OleDbConnection(ConnectionString)
Dim DeleteCommand As New OleDbCommand("DELETE FROM liste WHERE id=" & keyValue.ToString(), myConnection)
' execute the command
myConnection.Open()
DeleteCommand.ExecuteNonQuery()
myConnection.Close()
' rebind the grid
DataGrid1.CurrentPageIndex = 0
DataGrid1.EditItemIndex = -1
BindGrid()
End If
End Sub
Public Sub DataGrid_Page(Sender As Object, E As DataGridPageChangedEventArgs)
' display a new page of data
If Not isEditing Then
DataGrid1.EditItemIndex = -1
DataGrid1.CurrentPageIndex = e.NewPageIndex
BindGrid()
End If
End Sub
Public Sub AddNew_Click(Sender As Object, E As EventArgs)
' add a new row to the end of the data, and set editing mode 'on'
CheckIsEditing("")
If Not isEditing = True Then
' set the flag so we know to do an insert at Update time
AddingNew = True
' add new row to the end of the dataset after binding
' first get the data
Dim myConnection As New OleDbConnection(ConnectionString)
Dim myCommand As New OleDbDataAdapter(SelectCommand, myConnection)
Dim ds As New DataSet()
myCommand.Fill(ds)
' add a new blank row to the end of the data
Dim rowValues As Object() = {0,"", "", 0}
ds.Tables(0).Rows.Add(rowValues)
' figure out the EditItemIndex, last record on last page
Dim recordCount As Integer = ds.Tables(0).Rows.Count
If recordCount > 1 Then
recordCount -= 1
DataGrid1.CurrentPageIndex = recordCount \ DataGrid1.PageSize
DataGrid1.EditItemIndex = recordCount Mod DataGrid1.PageSize
End If
' databind
DataGrid1.DataSource = ds
DataGrid1.DataBind()
End If
End Sub
' ---------------------------------------------------------------
'
' Helpers Methods:
'
' property to keep track of whether we are adding a new record,
' and save it in viewstate between postbacks
Property AddingNew() As Boolean
Get
Dim o As Object = ViewState("AddingNew")
If o Is Nothing Then
Return False
End If
Return CBool(o)
End Get
Set(ByVal Value As Boolean)
ViewState("AddingNew") = Value
End Set
End Property
Public Sub BindGrid()
Dim myConnection As New OleDbConnection(ConnectionString)
Dim myCommand As New OleDbDataAdapter(SelectCommand, myConnection)
Dim ds As New DataSet()
myCommand.Fill(ds)
DataGrid1.DataSource = ds
DataGrid1.DataBind()
End Sub
</script>
<html>
<head>
<title>grid !!</title> <style type="text/css">INPUT {
BORDER-RIGHT: 0px; PADDING-RIGHT: 1px; BORDER-TOP: 0px; PADDING-LEFT: 1px; FONT-WEIGHT: normal; FONT-SIZE: 10px; PADDING-BOTTOM: 1px; MARGIN: 0px; BORDER-LEFT: 0px; WIDTH: 150px; COLOR: #000080; PADDING-TOP: 1px; BORDER-BOTTOM: 0px; FONT-FAMILY: Verdana; HEIGHT: 14px; BACKGROUND-COLOR: #ffffff
}
</style>
</head>
<body style="FONT-FAMILY: verdana">
<h2>grid !!
</h2>
<hr align="left" width="500" color="background" />
<form runat="server">
<asp:datagrid id="DataGrid1" runat="server" AutoGenerateColumns="False" CellSpacing="1" GridLines="None" CellPadding="2" BackColor="Silver" ForeColor="Black" OnPageIndexChanged="DataGrid_Page" AllowPaging="True" OnDeleteCommand="DataGrid_Delete" OnCancelCommand="DataGrid_Cancel" OnUpdateCommand="DataGrid_Update" OnEditCommand="DataGrid_Edit" OnItemCommand="DataGrid_ItemCommand" Font-Size="12px" Font-Names="Verdana">
<FooterStyle backcolor="Silver"></FooterStyle>
<HeaderStyle font-bold="True" forecolor="Desktop" backcolor="Silver"></HeaderStyle>
<PagerStyle font-size="Smaller" horizontalalign="Center" backcolor="#C6C3C6"></PagerStyle>
<AlternatingItemStyle backcolor="Highlight"></AlternatingItemStyle>
<ItemStyle forecolor="White" backcolor="Desktop"></ItemStyle>
<Columns>
<asp:BoundColumn DataField="id" HeaderText="ID">
<HeaderStyle width="20px"></HeaderStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="item_1" HeaderText="ITEM 1">
<HeaderStyle width="150px"></HeaderStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="item_2" HeaderText="ITEM 2">
<HeaderStyle width="150px"></HeaderStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="item_3" HeaderText="ITEM 3">
<HeaderStyle width="150px"></HeaderStyle>
</asp:BoundColumn>
<asp:EditCommandColumn ButtonType="LinkButton" UpdateText="update" CancelText="cancel" EditText="edit">
<HeaderStyle width="70px"></HeaderStyle>
</asp:EditCommandColumn>
<asp:ButtonColumn Text="delete" CommandName="Delete">
<HeaderStyle width="70px"></HeaderStyle>
</asp:ButtonColumn>
</Columns>
</asp:datagrid>
<br />
<asp:LinkButton id="LinkButton1" onclick="AddNew_Click" runat="server" Font-Size="smaller" Text="ny !!"></asp:LinkButton>
<br />
<br />
<asp:Label id="Message" runat="server" enableviewstate="false" forecolor="red"></asp:Label>
<br />
<br />
</form>
</body>
</html>
Håber en kan hjælpe mig. På forhånd tak.
