Working with the latest versions of vb.net and Asp.net, I would like to be allow the user to enter data directly into a gridview column without having to press edit and update. Only one column would be editable. Best would be to automatically move to the next row of the column upon hitting enter.
I have it set up where edit and update are not visible and thought a fix might be calling edit when selecting a row and update upon moving to a new row, but I can't find out how to do that.
This is easily doable with dataviewgrid in forms, ub I need to do it using the web.
Public Class PastureCnt
Inherits System.Web.UI.Page
Public provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = S:\Ranch\Data\"
Public dt As New DataTable
Public LocConn As New OleDbConnection(Provider & fGetDatabase())
Public Company As String
Dim _rowIndex As Integer
Dim LastRow As Integer
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
' Create a new table.
Dim mpLabel As Label = CType(Master.FindControl("lblTitle"), Label)
If Not mpLabel Is Nothing Then
mpLabel.Text = "Cattlemaster Ranch Pasture Count"
End If
Dim SQL = "SELECT Pasture, LotNo, [Current], Sex, ActualCount, Comment FROM Lots"
Dim LotAdapter As New OleDbDataAdapter(SQL, LocConn)
LotAdapter.Fill(dt)
Session("Lots") = dt
BindData()
End If
End Sub
Protected Overrides Sub Render(writer As HtmlTextWriter)
For Each r As GridViewRow In gvPastCnt.Rows
If r.RowType = DataControlRowType.DataRow Then
Page.ClientScript.RegisterForEventValidation(r.UniqueID + "$ctl00")
End If
Next
MyBase.Render(writer)
End Sub
Protected Sub gvPastCnt_RowCommand(sender As Object, e As GridViewCommandEventArgs)
Try
Dim _gridView As GridView = DirectCast(sender, GridView)
' Get the selected index
_rowIndex = Integer.Parse(e.CommandArgument.ToString())
Dim _columnIndex As Integer = Integer.Parse(Request.Form("__EVENTARGUMENT"))
'Dim _selectedIndex As Integer = Integer.Parse(e.CommandArgument.ToString())
_gridView.SelectedIndex = _rowIndex
'Me.Message.Text += "Single clicked GridView row at index " & _rowIndex.ToString() & "<br />"
' Get the display control for the selected cell and make it invisible
Dim _displayControl As Control = _gridView.Rows(_rowIndex).Cells(_columnIndex).Controls(1)
_displayControl.Visible = False
' Get the edit control for the selected cell and make it visible
Dim _editControl As Control = _gridView.Rows(_rowIndex).Cells(_columnIndex).Controls(3)
_editControl.Visible = True
' Clear the attributes from the selected cell to remove the click event
_gridView.Rows(_rowIndex).Cells(_columnIndex).Attributes.Clear()
' Get the display control for the selected cell and make it invisible
' Set focus on the selected edit control
ScriptManager.RegisterStartupScript(Me, [GetType](), "SetFocus", "document.getElementById('" + _editControl.ClientID & "').focus();", True)
' If the edit control is a dropdownlist set the
' SelectedValue to the value of the display control
If TypeOf _editControl Is DropDownList AndAlso TypeOf _displayControl Is Label Then
DirectCast(_editControl, DropDownList).SelectedValue = DirectCast(_displayControl, Label).Text
End If
' If the edit control is a textbox then select the text
If TypeOf _editControl Is TextBox Then
DirectCast(_editControl, TextBox).Attributes.Add("onfocus", "this.select()")
End If
' If the edit control is a checkbox set the
' Checked value to the value of the display control
If TypeOf _editControl Is CheckBox AndAlso TypeOf _displayControl Is Label Then
DirectCast(_editControl, CheckBox).Checked = Boolean.Parse(DirectCast(_displayControl, Label).Text)
End If
Catch ex As Exception
End Try
End Sub
Sub gvPastCnt_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvPastCnt.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
' Get the LinkButton control in the first cell
Dim _singleClickButton As LinkButton = DirectCast(e.Row.Cells(0).Controls(0), LinkButton)
' Get the javascript which is assigned to this LinkButton
Dim _jsSingle As String = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "")
' Add this javascript to the onclick Attribute of the row
'e.Row.Attributes("onclick") = _jsSingle
'For columnIndex As Integer = _firstEditCellIndex To e.Row.Cells.Count - 1
' Add the column index as the event argument parameter
Dim js As String = _jsSingle.Insert(_jsSingle.Length - 2, 5)
'Dim js As String = _jsSingle.Insert(_jsSingle.Length - 2, columnIndex.ToString())
' Add this javascript to the onclick Attribute of the cell
'e.Row.Cells(columnIndex).Attributes("onclick") = js
e.Row.Cells(3).Attributes("onclick") = js
' Add a cursor style to the cells
e.Row.Cells(3).Attributes("style") += "cursor:pointer;cursor:hand;"
'e.Row.Cells(columnIndex).Attributes("style") += "cursor:pointer;cursor:hand;"
'Next
End If
End Sub
Private Sub BindData()
gvPastCnt.DataSource = Session("Lots")
gvPastCnt.DataBind()
End Sub
Protected Sub gvPastCnt_RowDeleting(sender As Object, e As GridViewEditEventArgs)
'Set the edit index.
gvPastCnt.EditIndex = e.NewEditIndex
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub gvPastCnt_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles gvPastCnt.RowEditing
gvPastCnt.EditIndex = e.NewEditIndex
BindData()
End Sub
Protected Sub gvPastCnt_RowUpdating(sender As Object, ByVal e As GridViewUpdateEventArgs)
'Retrieve the table from the session object.
dt = CType(Session("Lots"), DataTable)
'Update the values.
Dim row = gvPastCnt.Rows(e.RowIndex)
dt.Rows(row.DataItemIndex)("ActualCount") = (CType((row.Cells(3).Controls(0)), TextBox)).Text
'Reset the edit index.
gvPastCnt.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub gvPastCnt_RowCancelingEdit()
'Reset the edit index.
gvPastCnt.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub gvPastCnt_Sorting(sender As Object, e As EventArgs) Handles gvPastCnt.Sorting
End Sub
Protected Sub gvPastCnt_SelectedIndexChanged(sender As Object, e As EventArgs) Handles gvPastCnt.SelectedIndexChanged
End Sub
Protected Sub gvPastCnt_RowCommand(sender As Object, e As EventArgs) Handles gvPastCnt.RowCommand
End Sub
End Class
Thanks for responding. I converted your C# to VB and entered it, so I could track exactly what is happening.
Everyting looks good except
Imports Microsoft.ApplicationBlocks.Data which it says doesn't contain any public member or can't be found. I commented it out, but the form won't load. With it in, my web page won't load.
Thanks again for responding. I am a newbe and am a little dense.
I downloaded the sample file. I don't understand how to use the sample. I use access as a database; so that shouldn't be a problem. Sample doesn't appear to be a db file.
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="PastureCnt.aspx.vb" Inherits="Ranch_Inventory.PastureCnt" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Enter Pasture Count</title>
</head>
<body>
<form id="form1" runat="server" >
<div style="text-align: center">
<asp:gridview ID="gvPastCnt" runat="server" OnRowDataBound="gvPastCnt_RowDataBound" AutoGenerateColumns="False" >
<HeaderStyle BackColor="#CC9900" />
<Columns>
<asp:BoundField DataField="Pasture" HeaderText="Pasture" ReadOnly="True" ItemStyle-Width="135" ItemStyle-BackColor="Wheat" >
<ItemStyle BackColor="Wheat" Width="135px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="LotNo" HeaderText="Lot" ReadOnly="True" ItemStyle-Width="50" ItemStyle-BackColor="Wheat">
<ItemStyle BackColor="Wheat" Width="50px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="Current" HeaderText="Cur Hd" ReadOnly="True" ItemStyle-Width="40" ItemStyle-BackColor="Wheat">
<ItemStyle BackColor="Wheat" Width="40px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="Sex" HeaderText="Sex" ReadOnly="True" ItemStyle-Width="60" ItemStyle-BackColor="Wheat">
<ItemStyle BackColor="Wheat" Width="60px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Pasture Count" >
<ItemTemplate>
<asp:TextBox ID="ActualCount" runat="server" MaxLength="4"></asp:TextBox>
</ItemTemplate>
<ControlStyle Width="100px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Comment" >
<ItemTemplate>
<asp:TextBox ID="Comment" runat="server"></asp:TextBox>
</ItemTemplate>
<ControlStyle Width="300px" />
</asp:TemplateField>
</Columns>
</asp:gridview>
<asp:Button ID="btnSubmit" runat="server" Font-Size="Medium" Text="Submit" BackColor="#CC9900" Font-Bold="True" style="text-align: left" />
</div>
</form>
</body>
</html>
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Dim cmd As New OleDbCommand
Dim textHead As TextBox
Dim Past As String
Dim LotNo As String
Dim row As GridViewRow
cmd.Connection = LocConn
LocConn.Open()
For rowI = 0 To gvPastCnt.Rows.Count - 1
cmd.Parameters.Clear()
row = DirectCast(gvPastCnt.Rows(rowI), GridViewRow)
Past = row.Cells(0).Text
LotNo = row.Cells(1).Text
textHead = DirectCast(row.FindControl("ActualCount"), TextBox)
cmd.CommandText = "UPDATE Lots SET ActualCount = @a0 WHERE Pasture = '" & fParseString(Past) & "' AND LotNo ='" & LotNo & "'"
With cmd.Parameters
.Add("@a0", OleDbType.Integer).Value = Val(textHead.Text)
End With
cmd.ExecuteNonQuery()
Next rowI
LocConn.Close()
cmd.Dispose()
okToSendMarkup = True
SendRenderedMarkup()
Server.Transfer("/ChcMenu.aspx")
End Sub
What I am doing it allowing data entry in a column of a table, not adding rows. I wanted it to automatically update the table once I pressed "submit"; however, my workaround was to loop through the table. Here is my code. Thanks everyone for your help.
jjobcorp
Member
9 Points
27 Posts
gridview allow column input without edit button
Oct 27, 2012 09:43 PM|LINK
<%@ Page Title="PastureCount" Language="vb" AutoEventWireup="true" MasterPageFile="~/Grid.Master" CodeBehind="PastureCnt.aspx.vb" Inherits="Ranch_Inventory.PastureCnt" %> <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server"></asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <asp:GridView ID="gvPastCnt" runat="server" AutoGenerateColumns="False" CellPadding="2" CellSpacing="2" EmptyDataText="There are no lots." ShowFooter="False" OnRowDataBound="gvPastCnt_RowDataBound" AllowSorting="True" OnRowCancelingEdit="gvPastCnt_RowCancelingEdit" CssClass="Normal" OnRowEditing="gvPastCnt_RowEditing" OnRowUpdating="gvPastCnt_RowUpdating" OnSorting="gvPastCnt_Sorting" OnRowCommand="gvPastCnt_RowCommand" EditIndex="5" > <%-- OnRowDeleting="gvPastCnt_RowDeleting" AutoGenerateEditButton="True" AutoGenerateDeleteButton="true" AllowPaging="True" PageSize="16" OnPageIndexChanging="gvPastCnt_PageIndexChanging" AutoGenerateSelectButton="True" OnSelectedIndexChanged="gvPastCnt_SelectedIndexChanged" --%> <Columns> <asp:ButtonField Text="SingleClick" CommandName="SingleClick" visible="false"/> <asp:BoundField DataField="Pasture" HeaderText="Pasture" SortExpression="Pasture" ReadOnly="True" ItemStyle-Width="135" > </asp:BoundField> <asp:BoundField DataField="LotNo" HeaderText="Lot" InsertVisible="False" ReadOnly="True" SortExpression="LotNo" ItemStyle-Width="50"></asp:BoundField> <asp:BoundField DataField="Current" HeaderText="Cur Hd" ReadOnly="True" ItemStyle-Width="40"></asp:BoundField> <%--<asp:BoundField DataField="ActualCount" HeaderText="Actual Count" ItemStyle-Width="40"></asp:BoundField>--%> <asp:TemplateField HeaderText="Actual Count" ItemStyle-Width="40"> <ItemTemplate> <asp:Label ID="lblActualCount" runat="server" Text='<%# Eval("ActualCount")%>'></asp:Label> <asp:TextBox ID="ActualCount" runat="server" Text='<%# Bind("ActualCount")%>' Width="175px" visible="false"></asp:TextBox> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Sex" HeaderText="Sex" SortExpression="Sex" ReadOnly="True" ItemStyle-Width="60"></asp:BoundField> <asp:templatefield> <itemtemplate> <asp:linkbutton id="btnEdit" runat="server" commandname="Edit" text="Edit" visible="false"/> </itemtemplate> <edititemtemplate> <asp:linkbutton id="btnUpdate" runat="server" commandname="Update" text="Update" visible="false"/> <asp:linkbutton id="btnCancel" runat="server" commandname="Cancel" text="Cancel" visible="false"/> </edititemtemplate> </asp:templatefield> </Columns> </asp:GridView> </asp:Content>Public Class PastureCnt Inherits System.Web.UI.Page Public provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = S:\Ranch\Data\" Public dt As New DataTable Public LocConn As New OleDbConnection(Provider & fGetDatabase()) Public Company As String Dim _rowIndex As Integer Dim LastRow As Integer Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then ' Create a new table. Dim mpLabel As Label = CType(Master.FindControl("lblTitle"), Label) If Not mpLabel Is Nothing Then mpLabel.Text = "Cattlemaster Ranch Pasture Count" End If Dim SQL = "SELECT Pasture, LotNo, [Current], Sex, ActualCount, Comment FROM Lots" Dim LotAdapter As New OleDbDataAdapter(SQL, LocConn) LotAdapter.Fill(dt) Session("Lots") = dt BindData() End If End Sub Protected Overrides Sub Render(writer As HtmlTextWriter) For Each r As GridViewRow In gvPastCnt.Rows If r.RowType = DataControlRowType.DataRow Then Page.ClientScript.RegisterForEventValidation(r.UniqueID + "$ctl00") End If Next MyBase.Render(writer) End Sub Protected Sub gvPastCnt_RowCommand(sender As Object, e As GridViewCommandEventArgs) Try Dim _gridView As GridView = DirectCast(sender, GridView) ' Get the selected index _rowIndex = Integer.Parse(e.CommandArgument.ToString()) Dim _columnIndex As Integer = Integer.Parse(Request.Form("__EVENTARGUMENT")) 'Dim _selectedIndex As Integer = Integer.Parse(e.CommandArgument.ToString()) _gridView.SelectedIndex = _rowIndex 'Me.Message.Text += "Single clicked GridView row at index " & _rowIndex.ToString() & "<br />" ' Get the display control for the selected cell and make it invisible Dim _displayControl As Control = _gridView.Rows(_rowIndex).Cells(_columnIndex).Controls(1) _displayControl.Visible = False ' Get the edit control for the selected cell and make it visible Dim _editControl As Control = _gridView.Rows(_rowIndex).Cells(_columnIndex).Controls(3) _editControl.Visible = True ' Clear the attributes from the selected cell to remove the click event _gridView.Rows(_rowIndex).Cells(_columnIndex).Attributes.Clear() ' Get the display control for the selected cell and make it invisible ' Set focus on the selected edit control ScriptManager.RegisterStartupScript(Me, [GetType](), "SetFocus", "document.getElementById('" + _editControl.ClientID & "').focus();", True) ' If the edit control is a dropdownlist set the ' SelectedValue to the value of the display control If TypeOf _editControl Is DropDownList AndAlso TypeOf _displayControl Is Label Then DirectCast(_editControl, DropDownList).SelectedValue = DirectCast(_displayControl, Label).Text End If ' If the edit control is a textbox then select the text If TypeOf _editControl Is TextBox Then DirectCast(_editControl, TextBox).Attributes.Add("onfocus", "this.select()") End If ' If the edit control is a checkbox set the ' Checked value to the value of the display control If TypeOf _editControl Is CheckBox AndAlso TypeOf _displayControl Is Label Then DirectCast(_editControl, CheckBox).Checked = Boolean.Parse(DirectCast(_displayControl, Label).Text) End If Catch ex As Exception End Try End Sub Sub gvPastCnt_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvPastCnt.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then ' Get the LinkButton control in the first cell Dim _singleClickButton As LinkButton = DirectCast(e.Row.Cells(0).Controls(0), LinkButton) ' Get the javascript which is assigned to this LinkButton Dim _jsSingle As String = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "") ' Add this javascript to the onclick Attribute of the row 'e.Row.Attributes("onclick") = _jsSingle 'For columnIndex As Integer = _firstEditCellIndex To e.Row.Cells.Count - 1 ' Add the column index as the event argument parameter Dim js As String = _jsSingle.Insert(_jsSingle.Length - 2, 5) 'Dim js As String = _jsSingle.Insert(_jsSingle.Length - 2, columnIndex.ToString()) ' Add this javascript to the onclick Attribute of the cell 'e.Row.Cells(columnIndex).Attributes("onclick") = js e.Row.Cells(3).Attributes("onclick") = js ' Add a cursor style to the cells e.Row.Cells(3).Attributes("style") += "cursor:pointer;cursor:hand;" 'e.Row.Cells(columnIndex).Attributes("style") += "cursor:pointer;cursor:hand;" 'Next End If End Sub Private Sub BindData() gvPastCnt.DataSource = Session("Lots") gvPastCnt.DataBind() End Sub Protected Sub gvPastCnt_RowDeleting(sender As Object, e As GridViewEditEventArgs) 'Set the edit index. gvPastCnt.EditIndex = e.NewEditIndex 'Bind data to the GridView control. BindData() End Sub Protected Sub gvPastCnt_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles gvPastCnt.RowEditing gvPastCnt.EditIndex = e.NewEditIndex BindData() End Sub Protected Sub gvPastCnt_RowUpdating(sender As Object, ByVal e As GridViewUpdateEventArgs) 'Retrieve the table from the session object. dt = CType(Session("Lots"), DataTable) 'Update the values. Dim row = gvPastCnt.Rows(e.RowIndex) dt.Rows(row.DataItemIndex)("ActualCount") = (CType((row.Cells(3).Controls(0)), TextBox)).Text 'Reset the edit index. gvPastCnt.EditIndex = -1 'Bind data to the GridView control. BindData() End Sub Protected Sub gvPastCnt_RowCancelingEdit() 'Reset the edit index. gvPastCnt.EditIndex = -1 'Bind data to the GridView control. BindData() End Sub Protected Sub gvPastCnt_Sorting(sender As Object, e As EventArgs) Handles gvPastCnt.Sorting End Sub Protected Sub gvPastCnt_SelectedIndexChanged(sender As Object, e As EventArgs) Handles gvPastCnt.SelectedIndexChanged End Sub Protected Sub gvPastCnt_RowCommand(sender As Object, e As EventArgs) Handles gvPastCnt.RowCommand End Sub End Classsarathi125
Star
13599 Points
2691 Posts
Re: gridview allow column input without edit button
Oct 28, 2012 08:54 AM|LINK
Hi,
Try like this, Its working fine when you pressing the enter key in the last column.
<div> <asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" > <Columns> <asp:BoundField DataField="RowNumber" HeaderText="Row Number" /> <asp:TemplateField HeaderText="dropdownlist1"> <ItemTemplate> <asp:DropDownList ID="ddl1" runat="server" ></asp:DropDownList> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="dropdownlist2"> <ItemTemplate> <asp:DropDownList ID="ddl2" runat="server" ></asp:DropDownList> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="dropdownlist3"> <ItemTemplate> <asp:DropDownList ID="ddl3" runat="server" ></asp:DropDownList> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="textbox1"> <ItemTemplate> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="textbox2"> <ItemTemplate> <asp:TextBox ID="TextBox2" runat="server" AutoPostBack="true" OnTextChanged="ButtonAdd_Click"></asp:TextBox> </ItemTemplate> </asp:TemplateField> </Columns> </asp:gridview> </div>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using System.Data.Sql; using Microsoft.ApplicationBlocks.Data; public partial class Default5 : System.Web.UI.Page { private void SetInitialRow() { DataTable dt = new DataTable(); DataRow dr = null; dt.Columns.Add(new DataColumn("RowNumber", typeof(string))); dt.Columns.Add(new DataColumn("dropdownlist1", typeof(string))); dt.Columns.Add(new DataColumn("dropdownlist2", typeof(string))); dt.Columns.Add(new DataColumn("dropdownlist3", typeof(string))); dt.Columns.Add(new DataColumn("textbox1", typeof(string))); dt.Columns.Add(new DataColumn("textbox2", typeof(string))); dr = dt.NewRow(); dr["RowNumber"] = 1; dr["dropdownlist1"] = string.Empty; dr["dropdownlist2"] = string.Empty; dr["dropdownlist3"] = string.Empty; dr["textbox1"] = string.Empty; dr["textbox2"] = string.Empty; dt.Rows.Add(dr); //Store the DataTable in ViewState ViewState["CurrentTable"] = dt; Gridview1.DataSource = dt; Gridview1.DataBind(); } private void AddNewRowToGrid() { int rowIndex = 0; if (ViewState["CurrentTable"] != null) { DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"]; DataRow drCurrentRow = null; if (dtCurrentTable.Rows.Count > 0) { for (int i = 1; i <= dtCurrentTable.Rows.Count; i++) { //extract the TextBox values DropDownList dl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("ddl1"); DropDownList dl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("ddl2"); DropDownList dl3 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("ddl3"); TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox1"); TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[5].FindControl("TextBox2"); drCurrentRow = dtCurrentTable.NewRow(); drCurrentRow["RowNumber"] = i + 1; try { dtCurrentTable.Rows[i - 1]["dropdownlist1"] = dl1.SelectedItem.ToString(); dtCurrentTable.Rows[i - 1]["dropdownlist2"] = dl2.SelectedItem.ToString(); dtCurrentTable.Rows[i - 1]["dropdownlist3"] = dl3.SelectedItem.ToString(); } catch (Exception e) { } dtCurrentTable.Rows[i - 1]["textbox1"] = box1.Text; dtCurrentTable.Rows[i - 1]["textbox2"] = box2.Text; rowIndex++; } dtCurrentTable.Rows.Add(drCurrentRow); ViewState["CurrentTable"] = dtCurrentTable; Gridview1.DataSource = dtCurrentTable; Gridview1.DataBind(); } } else { Response.Write("ViewState is null"); } //Set Previous Data on Postbacks SetPreviousData(); } private void SetPreviousData() { int rowIndex = 0; if (ViewState["CurrentTable"] != null) { DataTable dt = (DataTable)ViewState["CurrentTable"]; if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { DropDownList dl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("ddl1"); DropDownList dl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("ddl2"); DropDownList dl3 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("ddl3"); TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox1"); TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[5].FindControl("TextBox2"); box1.Text = dt.Rows[i]["textbox1"].ToString(); box2.Text = dt.Rows[i]["textbox2"].ToString(); dl1.Text = dt.Rows[i]["dropdownlist1"].ToString(); dl2.Text = dt.Rows[i]["dropdownlist2"].ToString(); dl3.Text = dt.Rows[i]["dropdownlist3"].ToString(); rowIndex++; } } } } protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { SetInitialRow(); } } protected void ButtonAdd_Click(object sender, EventArgs e) { AddNewRowToGrid(); } }Remember to click Mark as Answer on the post that helps to others.
My Blog :MyAspSnippets
jjobcorp
Member
9 Points
27 Posts
Re: gridview allow column input without edit button
Nov 03, 2012 03:19 PM|LINK
Thanks for responding. I converted your C# to VB and entered it, so I could track exactly what is happening.
Everyting looks good except
Imports Microsoft.ApplicationBlocks.Data which it says doesn't contain any public member or can't be found. I commented it out, but the form won't load. With it in, my web page won't load.
Thank you again.
sarathi125
Star
13599 Points
2691 Posts
Re: gridview allow column input without edit button
Nov 03, 2012 03:53 PM|LINK
Hi,
Oh,,, Sorry that is my DB Access class, microsoft provided it.
The link for that class is not working(OutDated). Check this link...
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=7912&lngWId=10
Here you can find the source for a gridview sample in that you can get the class.
Remember to click Mark as Answer on the post that helps to others.
My Blog :MyAspSnippets
jjobcorp
Member
9 Points
27 Posts
Re: gridview allow column input without edit button
Nov 03, 2012 04:32 PM|LINK
Thanks again for responding. I am a newbe and am a little dense.
I downloaded the sample file. I don't understand how to use the sample. I use access as a database; so that shouldn't be a problem. Sample doesn't appear to be a db file.
sarathi125
Star
13599 Points
2691 Posts
Re: gridview allow column input without edit button
Nov 04, 2012 08:07 AM|LINK
Hi,
That sample is fine to work with the SQL Server, I have uploaded the DB Backup file also there, try to customize it to Access DB.
Remember to click Mark as Answer on the post that helps to others.
My Blog :MyAspSnippets
vijay_myl
Contributor
5070 Points
1068 Posts
Re: gridview allow column input without edit button
Nov 04, 2012 04:19 PM|LINK
Hi..
why dont you use listview instead of using gridview..because listview have option to insert a direct data using sepearte templatefield..
also its have lot option to manipulate the data..
For more information about listview try the below links..
http://www.dotnetcode.in/2012/10/how-to-insertedit-and-delete-data-in.html
My .NET blog
Submit Article
graciax8
Participant
751 Points
210 Posts
Re: gridview allow column input without edit button
Nov 05, 2012 06:31 AM|LINK
You mean like these:
http://www.codeproject.com/Articles/467788/Dynamically-Adding-and-Deleting-rows-from-ASP-NET
http://www.codeproject.com/Articles/417693/Insert-Update-Delete-in-ASP-NET-Gridview-DataSourc
mycodepad.blogspot.com || TUMBLR
jjobcorp
Member
9 Points
27 Posts
Re: gridview allow column input without edit button
Nov 10, 2012 03:27 PM|LINK
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="PastureCnt.aspx.vb" Inherits="Ranch_Inventory.PastureCnt" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Enter Pasture Count</title> </head> <body> <form id="form1" runat="server" > <div style="text-align: center"> <asp:gridview ID="gvPastCnt" runat="server" OnRowDataBound="gvPastCnt_RowDataBound" AutoGenerateColumns="False" > <HeaderStyle BackColor="#CC9900" /> <Columns> <asp:BoundField DataField="Pasture" HeaderText="Pasture" ReadOnly="True" ItemStyle-Width="135" ItemStyle-BackColor="Wheat" > <ItemStyle BackColor="Wheat" Width="135px"></ItemStyle> </asp:BoundField> <asp:BoundField DataField="LotNo" HeaderText="Lot" ReadOnly="True" ItemStyle-Width="50" ItemStyle-BackColor="Wheat"> <ItemStyle BackColor="Wheat" Width="50px"></ItemStyle> </asp:BoundField> <asp:BoundField DataField="Current" HeaderText="Cur Hd" ReadOnly="True" ItemStyle-Width="40" ItemStyle-BackColor="Wheat"> <ItemStyle BackColor="Wheat" Width="40px"></ItemStyle> </asp:BoundField> <asp:BoundField DataField="Sex" HeaderText="Sex" ReadOnly="True" ItemStyle-Width="60" ItemStyle-BackColor="Wheat"> <ItemStyle BackColor="Wheat" Width="60px"></ItemStyle> </asp:BoundField> <asp:TemplateField HeaderText="Pasture Count" > <ItemTemplate> <asp:TextBox ID="ActualCount" runat="server" MaxLength="4"></asp:TextBox> </ItemTemplate> <ControlStyle Width="100px" /> </asp:TemplateField> <asp:TemplateField HeaderText="Comment" > <ItemTemplate> <asp:TextBox ID="Comment" runat="server"></asp:TextBox> </ItemTemplate> <ControlStyle Width="300px" /> </asp:TemplateField> </Columns> </asp:gridview> <asp:Button ID="btnSubmit" runat="server" Font-Size="Medium" Text="Submit" BackColor="#CC9900" Font-Bold="True" style="text-align: left" /> </div> </form> </body> </html> Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click Dim cmd As New OleDbCommand Dim textHead As TextBox Dim Past As String Dim LotNo As String Dim row As GridViewRow cmd.Connection = LocConn LocConn.Open() For rowI = 0 To gvPastCnt.Rows.Count - 1 cmd.Parameters.Clear() row = DirectCast(gvPastCnt.Rows(rowI), GridViewRow) Past = row.Cells(0).Text LotNo = row.Cells(1).Text textHead = DirectCast(row.FindControl("ActualCount"), TextBox) cmd.CommandText = "UPDATE Lots SET ActualCount = @a0 WHERE Pasture = '" & fParseString(Past) & "' AND LotNo ='" & LotNo & "'" With cmd.Parameters .Add("@a0", OleDbType.Integer).Value = Val(textHead.Text) End With cmd.ExecuteNonQuery() Next rowI LocConn.Close() cmd.Dispose() okToSendMarkup = True SendRenderedMarkup() Server.Transfer("/ChcMenu.aspx") End SubWhat I am doing it allowing data entry in a column of a table, not adding rows. I wanted it to automatically update the table once I pressed "submit"; however, my workaround was to loop through the table. Here is my code. Thanks everyone for your help.