I'm having this issue on displaying data into gridview. I want to display data from BindData into a custom made gridview as below. I have already tried
write the code on same page as html > working(but my senior engineer does not want that), so now I need to redo it by use back-end code and pass those (ID,Name,Age) into those label ID using dataset. how can I accomplished this?
<asp:GridView ID="MyGridView" runat="server" CellPadding="5" CssClass="ControlStyle"
ForeColor="#333333" Font-Size="8px" GridLines="Vertical" width="40%" CaptionAlign="Left"
PageSize="15" AllowPaging="True" OnPageIndexChanging="MyData_OnPageIndexChanging"
AutoGenerateColumns="False" enableEventValidation="false">
<Columns >
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:ImageButton ID="img" runat="server" ImageUrl="~/Images/arrow-2a.png" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lbl_ID" runat="server" Font-Size="10px" CssClass="ControlStyleUpperCase"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lbl_Name" runat="server" Font-Size="10px" CssClass="ControlStyleUpperCase"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<asp:Label ID="lbl_Age" runat="server" Font-Size="10px" CssClass="ControlStyleUpperCase"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
and I want to display below data.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not Me.IsPostBack Then
Me.BindData()
End If
End Sub
Private Sub BindData()
Dim sCon As String = "MyConnectionString"
Using con As New SqlConnection(sCon)
Using cmd As New SqlCommand(" select * from users ")
Dim sda As New SqlDataAdapter()
Try
cmd.Connection = con : con.Open()
sda.SelectCommand = cmd
Dim dt As New DataTable
sda.Fill(dt)
'BIND DATABASE WITH THE GRIDVIEW.
MyGridView.DataSource = dt
MyGridView.DataBind()
Catch ex As Exception
txtMsg.Text = ex.Message
End Try
End Using
End Using
End Sub
with above code, my page show nothing, just white canvas, where did I do wrong? please guide.
thanks
Thanks for your kind effort, I've manage to solve this issue by modified my code from this
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not Me.IsPostBack Then
Me.BindData()
End If
End Sub
into this
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindData()
End If
End Sub
I still don't know whats the different between those two but I've manage to get my results as expected.
I want to be able to take a selected item from a dropdown list, hit a button, and have that item added to a GridView to be viewed by the user. Right now, when I hit the + button, the grid displays, but the cells are blank. Any suggestions?
ASP code:
<tr>
<td valign="top" colspan="2">
<b>Agents Visited</b><br />
<asp:DropDownList SelectionMode="Multiple" runat="server" ID="agentsDropdown" Name="agentsDropdown" width="425"></asp:DropDownList>
</td>
<td valign="top">
<br />
<asp:Button id="agentButton" name="agentButton" runat="server" Text="+" OnClick="AddAgent" CssClass="buttonstyle" onmouseover="shade(this);" onmouseout="unshade(this);" />
</td>
</tr>
<tr>
<asp:GridView ID="agentGridView" Visible="False" AllowSorting="False" AllowPaging="False" Runat="server" AutoGenerateColumns="False" PageSize="20" >
<Columns>
<asp:TemplateField HeaderText="Agent">
<ItemTemplate>
<asp:Label ID="agentName" runat="server" Text=''></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<asp:Label ID="agentValue" runat="server" Text=''></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
</tr>
Initial GridView bind:
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack
agentGridView.DataSource = Nothing
agentGridView.Databind()
End If
End Sub
Additional code behind:
Protected Sub AddAgent(sender As Object, e As EventArgs)
If agentsDropdown.SelectedIndex > 0 Then
Dim dt As New DataTable
dt.Columns.Add("agentName")
dt.Columns.Add("agentValue")
Dim row1 As DataRow = dt.NewRow
row1.Item("agentName") = agentsDropdown.SelectedItem.Text.ToString()
row1.Item("agentValue") = agentsDropdown.SelectedValue.ToString()
dt.Rows.Add(row1)
agentGridView.DataSource = dt
agentGridView.DataBind()
agentsDropdown.SelectedIndex = 0
Dim agentRowsCount as Integer = agentGridView.Rows.Count
If agentRowsCount > 0
agentGridView.Visible = True
End If
End If
End Sub
This should work for you now. Change your GridView to the following:
<asp:GridView ID="agentGridView" Visible="False" AllowSorting="False" AllowPaging="False" Runat="server" AutoGenerateColumns="False" PageSize="20" >
<Columns>
<asp:BoundField DataField="agentName" HeaderText="Agent Name" ItemStyle-Width="30" />
<asp:BoundField DataField="agentValue" HeaderText="Agent Value" ItemStyle-Width="30" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
See if this will work for you. I am more c# however this looked like it worked:
Public Class WebForm1
Inherits System.Web.UI.Page
Dim dt = Nothing
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Session("Agents") Is Nothing) Then
dt = New DataTable
Else
dt = Session("Agents")
End If
If Not Page.IsPostBack Then
agentGridView.DataSource = Nothing
agentGridView.DataBind()
End If
End Sub
Protected Sub AddAgent(sender As Object, e As EventArgs) Handles agentsDropdown.SelectedIndexChanged
If agentsDropdown.SelectedIndex > 0 Then
If (Session("Agents") Is Nothing) Then
dt = New DataTable()
dt.Columns.Add("agentName")
dt.Columns.Add("agentValue")
End If
Dim row1 As DataRow = dt.NewRow
row1.Item("agentName") = agentsDropdown.SelectedItem.Text.ToString()
row1.Item("agentValue") = agentsDropdown.SelectedValue.ToString()
dt.Rows.Add(row1)
Session("Agents") = dt
agentGridView.DataSource = dt
agentGridView.DataBind()
agentsDropdown.SelectedIndex = 0
Dim agentRowsCount As Integer = agentGridView.Rows.Count
If agentRowsCount > 0 Then
agentGridView.Visible = True
End If
End If
End Sub
End Class
code sample aspx vb behind code:
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
For Each row As GridViewRow In GridView1.Rows
Dim checkbox As CheckBox = CType(row.FindControl("chkdelete"), CheckBox)
If checkbox.Checked Then
Dim ID As Integer = Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value)
SqlDataSource1.DeleteParameters("ID").DefaultValue = ID.ToString()
SqlDataSource1.Delete()
End If
Next row
front code :
`
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkdelete" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="No"
SortExpression="ID"/>
<asp:BoundField DataField="Name" HeaderText="Name"
SortExpression="Name"/>
<asp:CommandField Headertext="Edit" ShowEditButton="True" />
<asp:CommandField Headertext="Delete" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<asp:Button ID="btnDelete" runat="server" Text="Delete" onclick="btnDelete_Click"/>`
my question is, why my multiple delete still wont work? whats wrong with my code? anyone pls help..
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
For Each row As GridViewRow In GridView1.Rows
Dim checkbox As CheckBox = CType(row.FindControl("chkdelete"), CheckBox)
If checkbox.Checked Then
Dim ID As Integer = Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value)
Delete(ID)
End If
Next row
End Sub
Public Function Delete(ByRef ID as Integer)
' Your Connection Coding comes here
SqlDataSource1.DeleteParameters("ID").DefaultValue = ID.ToString()
SqlDataSource1.Delete()
End Function
Try This Way..!!
We have a GridView with a 2 buttons. One of the buttons is a select button and the other is a one without a command. It is supposed to activate an OnClick sub routine. The sub routine is not executing.
Here is the markup of the GridView with the buttons:
<asp:GridView
ID="GridViewParentsSummary"
runat="server"
AllowPaging="True"
AllowSorting="True"
AutoGenerateColumns="False"
DataKeyNames="ID"
>
<Columns>
<asp:BoundField
DataField="ID"
HeaderText="ID"
SortExpression="ID" InsertVisible="False" ReadOnly="True" Visible="False" />
<asp:BoundField
DataField="FatherName"
HeaderText="FatherName"
SortExpression="FatherName" />
<asp:BoundField DataField="MotherName" HeaderText="MotherName"
SortExpression="MotherName" />
<asp:ButtonField
ButtonType="Button"
CommandName="Select"
Text="Select Details" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button
ID="ButtonNewPersonToReleaseChildren"
runat="server"
CausesValidation="false"
Text="New Person To Release Children"
CommandArgument='<%# Eval("ID") %>'
OnClick="NewPersonToReleaseChildren" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is the VB.Net code-behind coding with the sub routines for the buttons:
Protected Sub GridViewParentsSummary_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridViewParentsSummary.SelectedIndexChanged
IntParentsID = GridViewParentsSummary.DataKeys(GridViewParentsSummary.SelectedIndex).Value
Response.Redirect("AuthorizationForChildReleaseDetails.aspx")
End Sub
Protected Sub NewPersonToReleaseChildren(sender As Object, e As EventArgs)
blnAddModeIsSelected = True
MsgBox("The button was clicked.")
Response.Redirect("AuthorizationForChildReleaseDetails.aspx")
End Sub
I'm sure I am missing some coding but don't know what that could be because the sub routine for the Select button works, but not the sub routine for NewPersonToReleaseChildren.
in gridview:
<asp:TemplateField HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"
FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:ImageButton ID="ImgBtnDel" runat="server" ImageUrl="~/Images/icon-delete.gif" CommandName="del"
CommandArgument='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
use aspButton or Imagebutton in gridview,in code behind:
Protected Sub gridview1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridview1.RowCommand
Dim myId As String = e.CommandArgument.ToString
If e.CommandName = "del" Then
ElseIf e.CommandName = "upd" Then
End If
End Sub
Add Handles Handles NewPersonToReleaseChildren.Click to your handler
Protected Sub NewPersonToReleaseChildren(sender As Object, e As EventArgs) Handles NewPersonToReleaseChildren.Click
blnAddModeIsSelected = True
//MsgBox("The button was clicked.")
Response.Redirect("AuthorizationForChildReleaseDetails.aspx")
End Sub
I don't think there is anything like MsgBox in asp.net. If the Handles does not work, replace that line with Throw New Exception("My Button was called") or put a break point on that line and press F5
When I click the "Edit" button of the gridview, it will show "Update" and "Cancel" button. But when I click "Update" button, it will not fire any event "RowUpdating", RowUpdated", "RowCommand"... It reload the page and then gridview disappear.
The following is my asp code:
<asp:GridView ID="Gridview1" runat="server" EnableViewState="False"
AutoGenerateColumns = "False" Font-Names = "Arial"
Font-Size = "10pt" AlternatingRowStyle-BackColor = "#C2D69B"
AutoGenerateEditButton="false"
AllowPaging ="True"
PageSize = "20"
OnRowCommand="GridView1_RowCommand"
OnRowDataBound="GridView1_RowDataBound"
OnRowEditing="GridView1_RowEditing"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating"
OnPageIndexChanging="GridView1_PageIndexChanging">
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<Columns>
<asp:BoundField DataField = "Name&Post" HeaderText = "Name & Post" ReadOnly ="true" />
<asp:TemplateField HeaderText="Working<br>Time">
<ItemTemplate>
<asp:Label ID="lb1_rosterkey" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Col1_RosterKey")%>' Visible ="false" ></asp:Label>
<asp:DropDownList ID="ddl1_shifttype" runat ="server" Enabled ="false" DataSourceID="SqlDataSource2" DataTextField ="en_name" DataValueField ="shift_type_key"> </asp:DropDownList>
<MKB:TimeSelector ID="Col1_StartTime" runat="server" DisplaySeconds="False" ReadOnly="true" MinuteIncrement="1" AmPm="AM" BorderColor="Silver"
Date="" Hour="07" Minute="0" SelectedTimeFormat="Twelve"> </MKB:TimeSelector>
<MKB:TimeSelector ID="Col1_EndTime" runat="server" DisplaySeconds="False" ReadOnly="true" MinuteIncrement="1" AmPm="PM" BorderColor="Silver"
Date="" Hour="07" Minute="0" SelectedTimeFormat="Twelve"> </MKB:TimeSelector>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddl1_shifttype" runat ="server" DataSourceID="SqlDataSource2" DataTextField ="en_name" DataValueField ="shift_type_key"></asp:DropDownList>
<MKB:TimeSelector ID="Col1_StartTime" runat="server" DisplaySeconds="False" MinuteIncrement="1" AmPm="AM" BorderColor="Silver"
Date="" Hour="07" Minute="0" SelectedTimeFormat="Twelve"> </MKB:TimeSelector>
<MKB:TimeSelector ID="Col1_EndTime" runat="server" DisplaySeconds="False" MinuteIncrement="1" AmPm="PM" BorderColor="Silver"
Date="" Hour="07" Minute="0" SelectedTimeFormat="Twelve"> </MKB:TimeSelector>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Leave/<br>TOIL">
<ItemTemplate>
<asp:CheckBox
ID="cb1_VL" Enabled="false" Text="VL"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_VL")%> />
<asp:CheckBox
ID="cb1_SL" Enabled="false" Text="SL"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_SL")%> />
<asp:CheckBox
ID="cb1_ML" Enabled="false" Text="ML"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_ML")%> />
<asp:CheckBox
ID="cb1_PH" Enabled="false" Text="PH"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_PH")%> />
<asp:CheckBox
ID="cb1_APH" Enabled="false" Text="APH"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_APH")%> />
<asp:CheckBox
ID="cb1_TOIL" Enabled="false" Text="TOIL"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_TOIL")%> />
<br />
<%#DataBinder.Eval(Container.DataItem, "Col1_Others")%>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox
ID="cb1_VL" Text="VL"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_VL")%> />
<asp:CheckBox
ID="cb1_SL" Text="SL"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_SL")%> />
<asp:CheckBox
ID="cb1_ML" Text="ML"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_ML")%> />
<asp:CheckBox
ID="cb1_PH" Text="PH"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_PH")%> />
<asp:CheckBox
ID="cb1_APH" Text="APH"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_APH")%> />
<asp:CheckBox
ID="cb1_TOIL" Text="TOIL"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_TOIL")%> />
<asp:TextBox ID="tb1_Others" runat="server" Width="50" Text='<%#DataBinder.Eval(Container.DataItem, "Col1_Others") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
......
The following is the VB code:
Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
'Set the edit index.
Gridview1.EditIndex = e.NewEditIndex
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub GridView1_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
'Reset the edit index.
Gridview1.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
'Retrieve the table from the session object.
Dim dt = CType(Session("dt"), DataTable)
'Update the values.
Dim row = Gridview1.Rows(e.RowIndex)
'Reset the edit index.
Gridview1.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub
Private Sub BindData()
Dim StartDateStr As String
StartDateStr = Trim(Request.QueryString("sd"))
StartDateStr = Left(StartDateStr, 10)
'date should be best in ISO format, i.e. yyyy-mm-ddTHH:mm:ss[.mmm] as "Set Dateformat dmy" is not supported by DataSet object
'StartDateStr = Right(StartDateStr, 4) & "-" & Mid(StartDateStr, 4, 2) & "-" & Left(StartDateStr, 2) & " T00:00:00"
Dim StartDate As DateTime
Dim EndDate As DateTime
StartDate = Convert.ToDateTime(StartDateStr)
EndDate = Format(DateAdd(DateInterval.Day, 6, StartDate), "dd/MM/yyyy")
g_header1 = StartDate 'Monday
g_header2 = Format(DateAdd(DateInterval.Day, 1, StartDate), "dd/MM/yyyy")
g_header3 = Format(DateAdd(DateInterval.Day, 2, StartDate), "dd/MM/yyyy")
g_header4 = Format(DateAdd(DateInterval.Day, 3, StartDate), "dd/MM/yyyy")
g_header5 = Format(DateAdd(DateInterval.Day, 4, StartDate), "dd/MM/yyyy")
g_header6 = Format(DateAdd(DateInterval.Day, 5, StartDate), "dd/MM/yyyy")
g_header7 = EndDate 'Sunday
Gridview1.DataSource = Session("dt")
Gridview1.DataBind()
End Sub
Protected Sub GridView1_DataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles Gridview1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow AndAlso e.Row.RowState = DataControlRowState.Edit Then
'If e.Row.RowType = DataControlRowType.DataRow Then
Dim row = DirectCast(e.Row.DataItem, DataRowView).Row
Dim Col1_StartTime = DirectCast(e.Row.FindControl("Col1_StartTime"), MKB.TimePicker.TimeSelector)
'set the TimePicker's Value here according to the Time-Value in the DataRow'
End If
End Sub
Protected Sub Gridview1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles Gridview1.RowCommand
If e.CommandName = "Update" Then
'Reset the edit index.
Gridview1.EditIndex = -1
'Bind data to the GridView control.
BindData()
End If
End Sub
Use buttons in asp:TemplateField with proper CommandName and it will fire the corresponding events.
Example
<asp:TemplateField>
<ItemTemplate>
<asp:Button id="btnEdit" runat="server" commandname="Edit" text="Edit" />
<asp:Button id="btnDelete" runat="server" commandname="Delete" text="Delete" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button id="btnUpdate" runat="server" commandname="Update" text="Update" />
<asp:Button id="btnCancel" runat="server" commandname="Cancel" text="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
I solved my problem.
I need to set CausesValidation="false"
make enableviewstate=true in gridview
did you write this at page load, if not add this
if me.ispostback= false then
'grid fill statement
end if
I'm not sure where your save/cancel buttons are located but you may need to add a command name to them as specified on MSDN
ie. <asp:buttonfield buttontype="Link" commandname="Update" text="Update"/>
I never used separate rowupdate/rowedit commands but i do use the following:
in my grid columns list, i'm adding the commandfield and images (optional for the buttons)
<asp:CommandField HeaderText="Edit" ButtonType="Image" ShowCancelButton="true" ShowEditButton="True"
EditImageUrl="../images/esig.gif" CancelImageUrl="../images/btn_close.gif"
UpdateImageUrl="../images/icn_ok.gif" />
I don't see this in your code.
a sample of a grid-editing as below
In the code behind, you should be able to check for the RowDataBound event as per below (Grida is the name of the sample grid)
Protected Sub Grida_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles Grida.RowDataBound
'check for row in edit mode
If (e.Row.RowState = DataControlRowState.Edit) then
' create handles for the row being edited
Dim drv As System.Data.DataRowView = CType(e.Row.DataItem, System.Data.DataRowView)
' locate the dropdownbox (in my page)
Dim dllven As DropDownList = CType(e.Row.Cells(3).FindControl("DropDownVendor"), DropDownList)
' check what item was selected in this DDL when in editmode
Dim li As ListItem = dllven.Items.FindByText(drv("Vendor").ToString)
' set the selection upon return
li.Selected = True
end if
End Sub
works perfectly for me.