How to implement datatable in a gridview in a master page - asp.net

I am using the AdminLTE library and have designed my master with 2 content placeholders; one in the head section and another in the body section. I am unable to get my gridview to render its content in a datatable.
I populate the gridview via a shared method from a class file which works fine. I have tried to write the Javascript document.ready function in the head section of my aspx form but the gridview seems not to recognize the function.
This is the markup
<div class="box">
<div class="box-header">
<h3 class="box-title">List of available regions</h3>
</div>
<div class="box-body">
<asp:GridView ID="grvRegions" runat="server" class="table table-bordered table-striped"
EmptyDataText="Empty region list" OnRowEditing="OnRowEditing"
OnRowCancelingEdit="OnRowCancelingEdit" OnRowUpdating="OnRowUpdating"
AutoGenerateColumns="False" DataKeyNames="ID" AllowPaging="True">
<Columns>
<asp:TemplateField HeaderText="ID" InsertVisible="False" SortExpression="ID">
<EditItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Eval("ID")%>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Region" InsertVisible="False" SortExpression="ID">
<EditItemTemplate>
<asp:TextBox ID="txtEditRegion" required="required" CssClass="form-control" MaxLength="50" runat="server" Text='<%# Eval("Region")%>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblRegion" runat="server" Text='<%# Bind("Region")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="lbtUpdate" CssClass="btn btn-success" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="lbtCancel" CssClass="btn btn-danger" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="lbtRemove" class="btn btn-info" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
This is the method that retrieves the data for the gridview
Public Shared Sub FillTabularData(container As Object, spName As String, Optional param As SqlParameter = Nothing)
Dim command As New SqlCommand(spName, connection)
command.CommandType = CommandType.StoredProcedure
If param IsNot Nothing Then
command.Parameters.Add(param)
End If
If connection.State = ConnectionState.Closed Then
connection.Open()
End If
Dim dTable As New DataSet
Dim dAdapter As SqlDataAdapter = New SqlDataAdapter(command)
dAdapter.Fill(dTable)
container.DataSource = dTable
container.DataBind()
End Sub
This is the calling of the "FillTabularData" method in my code behind file for the gridview
Sub BindData()
FillTabularData(grvRegions, "sp_list_regions")
grvRegions.UseAccessibleHeader = True
grvRegions.HeaderRow.TableSection = TableRowSection.TableHeader
End Sub
I expect the output to be rendered in a datatable with paging, sorting, searching and number of rows per page capabilities.

Try like this (I am not familiar with vb.net coding, please check the syntax)
Sub BindData()
Dim dt As New DataSet
dt= FillTabularData("sp_list_regions")
grvRegions.DataSource = dTable
grvRegions.DataBind()
grvRegions.UseAccessibleHeader = True
grvRegions.HeaderRow.TableSection = TableRowSection.TableHeader
End Sub
Public Shared Function FillTabularData(spName As String, Optional param As SqlParameter = Nothing) As DataSet
Dim command As New SqlCommand(spName, connection)
command.CommandType = CommandType.StoredProcedure
If param IsNot Nothing Then
command.Parameters.Add(param)
End If
If connection.State = ConnectionState.Closed Then
connection.Open()
End If
Dim dTable As New DataSet
Dim dAdapter As SqlDataAdapter = New SqlDataAdapter(command)
dAdapter.Fill(dTable)
return dTable
End Function

Related

Having difficulty populating a DropDownList within a GridView

As the title states I am having a lot of difficulty populating a drop down list that is within a gridview on my web form. I feel like this process should be relatively straight forward as I have populated many gridviews and drop down lists in the past without a hitch. Below, I have detailed what I have tried and will post any associated code. I am relatively new to software development and any help in solving this problem would be greatly appreciated.
To start I have added a drop down list to the gridview in question. Code below.
<asp:GridView ID="GridView3" runat="server"
EmptyDataText="No Claimed Parts" AutoGenerateColumns="False"
ShowHeaderWhenEmpty="True" DataKeyNames="RecID"
ShowFooter="True" DataSourceID="SqlDataSource5" Width="95%">
<EmptyDataTemplate>
<asp:DropDownList ID="ddlPartEquipmentNew" runat="server" DataSourceID="SqlDataSourcePartEquipment" DataValueField="EquipmentType" DataTextField="EquipmentType"
AppendDataBoundItems="True" Width="270px" Height="20px" Style="margin-left: 70px;">
<asp:ListItem Value="0">---SELECT---</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlPartNew" runat="server" DataSourceID="SqlDataSourcePart" DataValueField="RecID"
DataTextField="description" AppendDataBoundItems="True" Width="270px" Height="20px"
style="margin-left: 70px; margin-right: 110px">
<asp:ListItem Value="0">---SELECT---</asp:ListItem>
</asp:DropDownList>
<asp:textbox ID="txtUnitPriceNew" runat="server" Width="95px"/>
<asp:textbox ID="txtTaxNew" runat="server" Width="95px" text="0"/>
<asp:Button ID="InsertDetail" runat="server" CommandName="InsertDetail" Height="25px" Text="Add Detail" Width="85px" />
</EmptyDataTemplate>
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:CommandField ShowEditButton="True" footertext="Add -->" ShowDeleteButton="True" HeaderStyle-Width="70px"/>
<asp:BoundField DataField="RecID" HeaderText="RecID" SortExpression="RecID" ReadOnly="True" Visible="False" />
<asp:TemplateField HeaderText="Parts Description" ItemStyle-HorizontalAlign="center">
<ItemTemplate>
<asp:label ID="lblDescriptionAdd" Text='<%# Bind("PartFailed") %>' runat="server"/>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlPartEquipmentEdit" runat="server" DataValueField="Agreement" DataTextField="EquipmentType"
AppendDataBoundItems="True" Width="270px" Height="20px" Style="margin-left: 70px;">
<asp:ListItem Value="0">---SELECT---</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlPartEdit" runat="server" DataSourceID="SqlDataSourcePart" DataValueField="RecID" DataTextField="description" SelectedValue='<%# Eval("RepairID")%>' AppendDataBoundItems="True" Width="270px"/>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlPartEquipmentInsert" runat="server" DataValueField="Agreement" DataTextField="EquipmentType"
AppendDataBoundItems="True" Width="270px" Height="20px" Style="margin-left: 70px;">
<asp:ListItem Value="0">---SELECT---</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlPartInsert" runat="server" DataSourceID="SqlDataSourcePart" DataValueField="RecID" DataTextField="description" AppendDataBoundItems="True" Width="270px">
<asp:ListItem Value="0">---SELECT---</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Part Cost Requested" ItemStyle-HorizontalAlign="center" HeaderStyle-Width="100px">
<ItemTemplate>
<asp:label ID="lblUnitPrice" Text='<%# Bind("PartCost", "{0:C}") %>' runat="server" Enabled="False"/>
</ItemTemplate>
<EditItemTemplate>
<asp:textbox ID="txtUnitPriceEdit" Text='<%# Bind("PartCost") %>' Enabled="true" runat="server"/>
</EditItemTemplate>
<FooterTemplate>
<asp:textbox ID="txtUnitPriceInsert" Text='<%# Bind("PartCost") %>' runat="server" style="width: 100%; box-sizing: border-box;"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tax" ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="100px">
<ItemTemplate>
<asp:LinkButton ID="lbTaxTotal" Text='<%# Bind("Tax", "{0:C}")%>' runat="server" CommandArgument="Part" OnClick="lblTaxTotal_Click"/>
<asp:HiddenField ID="hidPartGST" runat="server" Value='<%# Bind("GST")%>' />
<asp:HiddenField ID="hidPartPST" runat="server" Value='<%# Bind("PST")%>' />
<asp:HiddenField ID="hidPartQST" runat="server" Value='<%# Bind("QST")%>' />
<asp:HiddenField ID="hidPartHST" runat="server" Value='<%# Bind("HST")%>' />
</ItemTemplate>
<EditItemTemplate>
<asp:textbox ID="lblTaxTotalEdit" Text='<%# Bind("Tax")%>' Enabled="true" runat="server"/>
</EditItemTemplate>
<FooterTemplate>
<asp:textbox ID="txtTaxTotalInsert" Text="0" runat="server" Enabled="true" style="width: 100%; box-sizing: border-box;"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Insert New" HeaderStyle-Width="85px">
<ItemTemplate>
<asp:Label ID="lblEmpty" Text="" runat="server" Width="75px"/>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="Insert" runat="server" CommandName="InsertNewDetail" Height="22px" Text="Insert" style="width: 100%; box-sizing: border-box;" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#336699" ForeColor="White" />
</asp:GridView>
In the above code, the gridview is declared and there are a series of controls within the gridview. The control in question is "ddlPartEquipmentNew" (technically I am having the same problem with the 2 other drop downs labeled "ddlPartEquipmentEdit" and "ddlPartEquipmentInsert" respectively, however we can ignore those at the moment.)
For whatever reason I cannot seem to figure out how to bind this ddl to the appropriate values I have in my database.
Below I will go into detail on what I have tried and the various outputs I have gotten.
One of the first things I have tried was to create a GetData() Function and then call that function in the gridviews OnDataBound() event, however when doing this, though I don't receive an error, the drop down has no values other than the default "---SELECT---" I setup in the aspx code above.
Below I have attached the code for the GetData() function and code for the OnDataBound() procedure.
GetData()
Private Function GetEquipmentData(query As String) As DataSet
Dim conString As SqlConnection = objCn
Dim cmd As New SqlCommand(query)
Using conString
Using sda As New SqlDataAdapter()
cmd.Connection = conString
sda.SelectCommand = cmd
Using ds As New DataSet()
sda.Fill(ds, txtAgreement.Text)
Return ds
End Using
End Using
End Using
End Function
OnDataBound()
Protected Sub GridView3_DataBound(sender As Object, e As EventArgs) Handles GridView3.DataBound
Dim partRequestedTotal As Decimal = Decimal.Zero
Dim partTotal As Decimal = Decimal.Zero
Dim gv As GridView = sender
If gv.EditIndex = -1 Then
For Each row As GridViewRow In gv.Rows
If row.RowType = DataControlRowType.DataRow Then
Dim lblAmount As Label = row.FindControl("lblUnitPrice")
Dim lblAmountRequested As Label = row.FindControl("lblUnitPrice")
Dim ddlPartEquipmentNew As DropDownList = row.FindControl("ddlPartEquipmentNew")
ddlPartEquipmentNew.DataSource = GetEquipmentData("SELECT EquipmentType FROM Equipment WHERE Agreement = #Agreement")
ddlPartEquipmentNew.DataTextField = "EquipmentType"
ddlPartEquipmentNew.DataValueField = "EquipmentType"
ddlPartEquipmentNew.DataBind()
'Dim lblMarkup As Label = row.FindControl("lblMarkup")
Dim partRequested As Decimal = Decimal.Parse(lblAmountRequested.Text, NumberStyles.Currency)
'Convert.ToDecimal(lblAmountRequested.Text.Replace("$", ""))
Dim partValue As Decimal = Decimal.Parse(lblAmount.Text, NumberStyles.Currency)
'Convert.ToDecimal(lblAmount.Text.Replace("$", ""))
'Dim markupValue As Decimal = Decimal.Parse(lblMarkup.Text, NumberStyles.Currency)
'Convert.ToDecimal(lblMarkup.Text.Replace("$", ""))
'partTotal = partValue + partTotal + markupValue
partRequestedTotal = partRequestedTotal + partRequested
End If
Next
'txtPartsTotal.Text = partTotal.ToString
txtPartsRequested.Text = partRequestedTotal.ToString("N2")
If GridView3.Rows.Count > 0 Or GridView1.Rows.Count > 0 Then
calculateTotalTax()
calculateTotal()
Else
txtTax.Text = "0"
Me.txtGrandTotal.Text = "0"
End If
End If
End Sub
With this attempt at binding the drop down list I receive no errors however the drop down in question remains empty.
I have also tried to create a databind event for the drop down list specifically and in the OnDataBind() event for the control I reference the procedure I created, however when I do this I get an exception error stating that I have a connection to the database that has not been closed, or a timeout exception.
Below is the code for the ddl databind event
Protected Sub DDLPartEquipmentNew_DataBind(sender As Object, e As EventArgs)
Dim ddlPartEquipmentNew As DropDownList = sender
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("WarrantyConnectionString").ToString)
Using cmd As New SqlCommand("SELECT EquipmentType FROM Equipment WHERE Agreement = #Agreement")
cmd.Parameters.Add("#Agreement", SqlDbType.Int).Value = txtAgreement.Text
cmd.CommandType = CommandType.Text
con.Open()
cmd.Connection = con
ddlPartEquipmentNew.DataSource = cmd.ExecuteReader()
ddlPartEquipmentNew.DataBind()
con.Close()
End Using
End Using
End Sub
As a last note on the situation I am having, the other drop down controls in this gridview are populated using an asp:SqlDataSource control which I have also tried, the issue I run into using a datasource in the aspx page is that my query requires a variable and so far I have not found a way to declare that variable in the code behind to avoid the exception "Must declare Scalar Variable #Agreement". The especially weird part about this exception is that in the stack trace it is popping this exception inside the databind event for a different gridview.
Query in question: SELECT EquipmentType FROM Equipment WHERE Agreement = #Agreement
Relatively simple, or at least I would think so. Any help someone would be able to offer on this problem would be greatly appreciated as I am at a loss as to how to populate this drop down, let alone any other drop down lists I may have to add to the page.

"Object reference not set to an instance of an object." error when updating GridView in asp.net

I'm trying to update GridView from code behind but stuck at a problem which I don't understand even after countless searches for a solution.
After editing a textbox in GridView EditItemTemplate, clicking an 'Update' button in the row would fire RowUpdating event. In the RowUpdating event handler, I use this code to get the string of the edited txtBox1:
Dim text1 As String = (CType(GridView1.Rows(e.RowIndex).FindControl("txtBox1"), TextBox)).Text
I am able to get a correct value for text1 but the problem is if I wrote GridView1.DataBind() in the same even handler, the code above will cause the error "Object reference not set to an instance of an object." I could not understand why the same code will work if delete/comment out GridView.DataBind() method.
I've been stuck with this problem for many days and I will really really appreciate any help.
Here's my VB.net code to handle GridView1.RowUpdating. This will only work if I delete or comment out GridView1.DataBind() method but GridView won't be updated with new data :
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs) Handles GridView1.RowUpdating
Dim text1 As String = (CType(GridView1.Rows(e.RowIndex).FindControl("txtBox1"), TextBox)).Text
Dim text2 As String = (CType(GridView1.Rows(e.RowIndex).FindControl("txtBox2"), TextBox)).Text
Dim IDkey As String = GridView1.DataKeys(e.RowIndex).Values(0).ToString()
Dim sqlquery As String = "UPDATE tblPMU SET zone = '" & text1 & "', substation ='" & text2 & "' WHERE (ID ='" & IDKey & "')"
Dim sqlCmd As New SqlCommand(sqlquery, conn)
Dim sqlDa As New SqlDataAdapter(sqlCmd)
conn.open()
Dim dt As New DataTable()
sqlDa.Fill(dt)
conn.Close()
GridView1.EditIndex = -1
UpdateGridview()
GridView1.DataBind()
Label5.Text=text1
End Sub
My .aspx code for the GridView:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" AllowSorting="True"
onrowediting="GridView1_RowEditing"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowupdating="GridView1_RowUpdating">
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" ReadOnly="True" Visible="False" />
<asp:TemplateField HeaderText="subzone" SortExpression="zone">
<EditItemTemplate>
<asp:TextBox ID="txtBox1" runat="server" Text='<%# Bind("zone") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("zone") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="substation" SortExpression="station">
<EditItemTemplate>
<asp:TextBox ID="txtBox2" runat="server" Text='<%# Bind("station") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("station") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Editable gridview is not working

I have an editable gridview which the user can edit each row just by pressing linkbutton. I am getting an error and it stops my work. please help me.
HTML
<asp:GridView ID="gvList" runat="server" class="gv" CellPadding="2"
Font-Names="Calibri" ForeColor="#333333"
Font-Size="16px" Width="500px" AutoGenerateColumns="true" OnRowCancelingEdit="gvList_RowCancelingEdit"
OnRowEditing="gvList_RowEditing" OnRowUpdating="gvList_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="User Name" HeaderStyle-ForeColor="White" HeaderStyle-Font-Bold="true" ItemStyle-Width="170px">
<ItemTemplate>
<asp:Label runat="server" ID="lblUsername" Text='<%# Eval("cUserName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="Editusername" runat="server" Text='<%# Eval("cUserName") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dept User" HeaderStyle-ForeColor="White" HeaderStyle-Font-Bold="true" ItemStyle-Width="170px">
<ItemTemplate>
<asp:Label runat="server" ID="lblDept" Text='<%# iif(Eval("lDeptUser"),"Yes","No") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:RadioButtonList ID="RadioButtonList1" runat="server" >
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:RadioButtonList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Actions" HeaderStyle-ForeColor="White" HeaderStyle-Font-Bold="true" ItemStyle-Width="160px">
<ItemTemplate>
<asp:LinkButton ID="btnedit" CommandName="Edit" runat="server" Text="Edit" />
<asp:LinkButton ID="btnDelete" CommandName="Delete" runat="server" Text="Delete" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" CommandName="Update" runat="server" Text="Update" />
<asp:LinkButton ID="btnCancel" CommandName="Cancel" runat="server" Text="Cancel" />
</EditItemTemplate>
<HeaderStyle Font-Bold="True" ForeColor="White"></HeaderStyle>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
No records available
</EmptyDataTemplate>
<HeaderStyle BackColor="#808380" Font-Bold="True" ForeColor="White" VerticalAlign="Top" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="#E3E3E3" />
</asp:GridView>
VB
Protected Sub gvList_RowUpdating(sender As Object, e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gvList.RowUpdating
Dim oldname = DirectCast(gvList.Rows(e.RowIndex).FindControl("lblUsername"), Label)
Dim username As String = DirectCast(gvList.Rows(e.RowIndex).FindControl("Editusername"), TextBox).Text
Dim tempUser = DirectCast(gvList.Rows(e.RowIndex).FindControl("RadioButtonList1"), RadioButtonList).SelectedIndex
Dim query As String = "Update Intranet.dbo.Gn_ISCoordinators SET cUserName=#uname" +
",lDeptUser=#dept WHERE cUserName=#oldName"
Using con = New SqlConnection(ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
con.Open()
Dim cmd = New SqlCommand(query, con)
cmd.Parameters.AddWithValue("#uname", username)
cmd.Parameters.AddWithValue("#dept", Convert.ToByte(tempUser))
cmd.Parameters.AddWithValue("#oldname", oldname)
cmd.ExecuteNonQuery()
End Using
gvList.EditIndex = -1
GetList()
End Sub
The problem is on the cmd.ExecuteNonQuery() it gives me The parameterized query '(#uname nvarchar(7),#dept tinyint,#oldname nvarchar(4000))Update' expects the parameter '#oldname', which was not supplied.
Any thing wrong in my query?
Try this
Dim oldname as Label =gvList.Rows(e.RowIndex).FindControl("lblUsername")
Dim username as TextBox = gvList.Rows(e.RowIndex).FindControl("Editusername")
Dim tempUser as RadioButtonList = DirectCast(gvList.Rows(e.RowIndex).FindControl("RadioButtonList1"), RadioButtonList).SelectedIndex
Dim query As String = "Update Intranet.dbo.Gn_ISCoordinators SET cUserName=#uname" +
",lDeptUser=#dept WHERE cUserName=#oldname"
Using con = New SqlConnection(ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
con.Open()
Dim cmd = New SqlCommand(query, con)
cmd.Parameters.AddWithValue("#uname", username.Text)
cmd.Parameters.AddWithValue("#dept", Convert.ToByte(tempUser.SelectedIndex))
cmd.Parameters.AddWithValue("#oldname", oldname.Text)
cmd.ExecuteNonQuery()
End Using
you have change the parameter name by making "N" capital in #oldName,so due to that
you are getting that Error
there is a typo in your parameter
Dim query As String = "Update Intranet.dbo.Gn_ISCoordinators SET cUserName=#uname" +
",lDeptUser=#dept WHERE cUserName=#oldName"
And you have
cmd.Parameters.AddWithValue("#oldname", oldname)
isn't it should be
cmd.Parameters.AddWithValue("#oldName", oldname)
there is capital and small letter mistake.
Sorry I dont have enough rep to comment so I have to answer here...
Why are you casting label to label and trying to use it as string?:
Dim oldname as string = DirectCast(gvList.Rows(e.RowIndex).FindControl("lblUsername"), Label).text
seems more appropriate.
Im not sure about this but maybe because when you tried to hit the edit button and the gridview's mode is in edit mode the lblUsername label will be changed to Editusername textbox.. So what I suggest is you try to put a global variable string that will store the data of the lblUsername before updating or editing..
Try this
Code look fine, but this line command.commandtype = commandtype.text is missing may be that the problem.
Also while passing parameter Addwithvalue use username.text instead on username same for other controls too
Dim oldname As Label = DirectCast(gvList.Rows(e.RowIndex).FindControl("lblUsername"), Label)
Dim username As TextBox = DirectCast(gvList.Rows(e.RowIndex).FindControl("Editusername"), TextBox).Text
Dim tempUser As RadioButton = DirectCast(gvList.Rows(e.RowIndex).FindControl("RadioButtonList1"), RadioButtonList).SelectedIndex
Dim query As String = "Update Intranet.dbo.Gn_ISCoordinators SET cUserName=#uname, lDeptUser=#dept WHERE cUserName=#oldName"
Using con = New SqlConnection(ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
con.Open()
Dim cmd = New SqlCommand(query, con)
cmd.commandtype = commandtype.text
cmd.Parameters.AddWithValue("#uname", username.text)
cmd.Parameters.AddWithValue("#dept", Convert.ToByte(tempUser.selectedvalue))
cmd.Parameters.AddWithValue("#oldname", oldname.text)
cmd.ExecuteNonQuery()
End Using
gvList.EditIndex = -1
GetList()

Get value from a textBox in Datalist linked with event button

This is my datalist:
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1"
RepeatLayout="Flow">
<ItemTemplate>
<asp:Label ID="IdLabel" runat="server" Text='<%# Eval("ID") %>' Visible="False" />
Titre:
<asp:Label ID="TitreLabel" runat="server" Text='<%# Eval("Titre") %>' />
<br />
Description:
<asp:Label ID="DescriptionLabel" runat="server"
Text='<%# Eval("Description") %>' />
<br />
<asp:Image ID="Image1" runat="server"
ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}") %>' Width="200" Height="200"/>
<br />
comments:
<asp:Label ID="commentsLabel" runat="server" Text='<%# Eval("comments") %>' />
<br />
Ajouter commentaire
<asp:button ID="btnAjouter" runat="server" OnCommand="Button_Command"
CommandName="add" Text="Ajouter" />
<asp:TextBox ID="TextBoxComments" runat="server"></asp:TextBox>
<br/>
<br/>
</ItemTemplate>
</asp:DataList>
This my aspx.vb button event:
Sub Button_Command(ByVal sender As Object, ByVal e As CommandEventArgs)
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("BecsEtMuseauxSQL").ConnectionString
Dim con As SqlConnection = New SqlConnection(connectionString)
con.Open()
Dim cmd As New SqlCommand("updateComments", con)
cmd.CommandType = CommandType.StoredProcedure
//I try this ....
cmd.Parameters.Add("#id", SqlDbType.Int).Value = DataList1.FindControl("IdLabel").ToString()
cmd.Parameters.Add("#Comments", SqlDbType.NVarChar).Value = DataList1.FindControl("TextBoxComments").ToString()
cmd.ExecuteNonQuery()
End Sub
I get an error like this: "The object reference is not definied to an object instance"
How can I catch the value from the label IdLabel and TextBoxComments in this situation?
You should handle the DataList's ItemCommand instead of the Button's Command.
Then you can find your controls with e.Item.FindControl:
Private Sub DataList1_ItemCommand(source As Object, e As System.Web.UI.WebControls.DataListCommandEventArgs) _
Handles DataList1.ItemCommand
If e.CommandName = "add" Then
Dim IdLabel = DirectCast(e.Item.FindControl("IdLabel"), Label)
Dim TextBoxComments = DirectCast(e.Item.FindControl("TextBoxComments"), TextBox)
' ... '
End If
End Sub
on aspx, remove your redundant Command-handler:
<asp:button ID="btnAjouter" CommandName="add" Text="Ajouter" runat="server" />
If you want to use the Button's Click-Event instead, that's possible also.
Protected Sub btnAjouter_Click(sender As Object, e As EventArgs)
Dim container = DirectCast(DirectCast(sender, Control).NamingContainer, DataListItem)
Dim IdLabel = DirectCast(container.FindControl("IdLabel"), Label)
Dim TextBoxComments = DirectCast(container.FindControl("TextBoxComments"), TextBox)
' ... '
End Sub
on aspx, add the click-event handler to the button:
<asp:button ID="btnAjouter" OnClick="btnAjouter_Click" Text="Ajouter" runat="server" />

CollapsiblePanelExtender in nested Repeater and Gridview setup doesn't function

I have a setup using three levels of nesting: A Repeater, the items of which utilize CollapsiblePanelExtenders (which work), and each contain a GridView. Each of these then contain another GridView which is controlled by another CollapsiblePanelExtender. These inner CollapsiblePanels will effectively show either an expanded or collapsed state only if I set clientState to True. However, they do not effectively expand or collapse as expected. Everything is bound dynamically.
Here is the markup...
<asp:Repeater ID="cat_repeater" runat="server">
<ItemTemplate>
<asp:CollapsiblePanelExtender id="cat_cpExt" runat="server" TargetControlID="cat_pnl" CollapsedSize="0" Collapsed="false" CollapsedImage="collapsed.png" ExpandedImage="expanded.png" ExpandControlID="cpControl_pnl" CollapseControlID="cpControl_pnl" TextLabelID="cpControl_lbl" ImageControlID="cpControl_img" CollapsedText='<%#configCPText(eval("Title"), False)%>' ExpandedText='<%#configCPText(eval("Title"), True) %>' />
<asp:Panel ID="cpControl_pnl" runat="server" Visible='<%#itemVisible(eval("ID"), "Recipients", "CategoryID") %>' CssClass="CPanelStyle">
<asp:Image ID="cpControl_img" runat="server" ImageUrl="expanded.png" />
<asp:Label ID="cpControl_lbl" runat="server" Text='<%#configCPText(eval("Title"), True) %>' CssClass="CPanelText" />
</asp:Panel>
<asp:Panel ID="cat_pnl" runat="server">
<asp:GridView ID="recipients_gv" runat="server" CssClass="GVStyle" HeaderStyle-CssClass="GVHeaderStyle" RowStyle-CssClass="GVItemStyle" AutoGenerateColumns="false" GridLines="none" AllowPaging="false">
<Columns>
<asp:TemplateField HeaderText="Name" SortExpression="Last Name" ItemStyle-CssClass="GVNameStyle">
<ItemTemplate>
<asp:Literal id="name_lit" runat="server" text='<%#formatNameText(eval("FirstName"), eval("LastName")) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Gifts" ItemStyle-Width="500px">
<ItemTemplate>
<asp:CollapsiblePanelExtender id="gifts_cpExt" runat="server" TargetControlID="gifts_pnl" CollapsedSize="0" Collapsed="true" CollapsedImage="collapsed.png" ExpandedImage="expanded.png" ExpandControlID="cpControl_pnl2" CollapseControlID="cpControl_pnl2" TextLabelID="cpControl_lbl2" ImageControlID="cpControl_img2" CollapsedText='<%#configGiftsCPText(eval("ID"), True)%>' ExpandedText='<%#configGiftsCPText(eval("ID"), False) %>' />
<asp:Panel ID="cpControl_pnl2" runat="server" Visible='<%#itemVisible(eval("ID"), "Gifts", "RecipientID") %>'>
<asp:Image ID="cpControl_img2" runat="server" ImageUrl="collapsed.png" />
<asp:Label ID="cpControl_lbl2" runat="server" Text='<%#configGiftsCPText(eval("ID"), False) %>' />
</asp:Panel>
<asp:Panel ID="gifts_pnl" runat="server">
<asp:GridView ID="gifts_gv" runat="server" DataKeyNames="ID" RowStyle-CssClass="GVInnerItemStyle" HeaderStyle-CssClass="GVInnerHeaderStyle" Gridlines="None" AutoGenerateColumns="false" AllowPaging="false" Width="475px">
<Columns>
<asp:TemplateField ItemStyle-CssClass="GVInnerButtonItemStyle" HeaderText="Description">
<ItemTemplate>
<asp:LinkButton ID="gift_lBtn" runat="server" Text='<%#eval("Description") %>' CommandName="Select" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Complete" ItemStyle-Width="50px">
<ItemTemplate>
<asp:CheckBox ID="giftComplete_cbx" runat="server" Checked='<%#eval("Complete") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
<br />
</ItemTemplate>
</asp:Repeater>
...And here is the code to bind everything:
Protected Sub bindCategories()
Try
oCmd.Connection = oConn
oCmd.CommandType = CommandType.Text
strSQL = "SELECT * FROM Categories"
oCmd.CommandText = strSQL
oDA.SelectCommand = oCmd
oDA.Fill(oDTbl)
cat_repeater.DataSource = oDTbl
cat_repeater.DataBind()
For i As Integer = 0 To oDTbl.Rows.Count - 1
oCmd.Parameters.Clear()
inner_dTbl.Clear()
strSQL = "SELECT *, Title FROM Recipients INNER JOIN Categories on Recipients.CategoryID = Categories.ID WHERE CategoryID = #CategoryID ORDER BY LastName"
oParam = New SqlParameter
oParam.ParameterName = "CategoryID"
oParam.SqlDbType = SqlDbType.Int
oParam.Value = oDTbl.Rows(i)("ID")
oCmd.Parameters.Add(oParam)
oCmd.CommandText = strSQL
oDA.SelectCommand = oCmd
oDA.Fill(inner_dTbl)
Dim gv As GridView = CType(cat_repeater.Items(i).FindControl("recipients_gv"), GridView)
gv.DataSource = inner_dTbl
gv.DataBind()
For j As Integer = 0 To inner_dTbl.Rows.Count - 1
oCmd.Parameters.Clear()
gifts_dTbl.Clear()
strSQL = "SELECT * FROM Gifts WHERE RecipientID = #RecipientID ORDER BY Description"
oParam = New SqlParameter
oParam.ParameterName = "RecipientID"
oParam.SqlDbType = SqlDbType.Int
oParam.Value = inner_dTbl.Rows(j)("ID")
oCmd.Parameters.Add(oParam)
oCmd.CommandText = strSQL
oDA.SelectCommand = oCmd
oDA.Fill(gifts_dTbl)
Dim inner_gv As GridView = CType(gv.Rows(j).FindControl("gifts_gv"), GridView)
inner_gv.DataSource = gifts_dTbl
inner_gv.DataBind()
Dim cpExt As CollapsiblePanelExtender = CType(gv.Rows(j).FindControl("gifts_cpExt"), CollapsiblePanelExtender)
cpExt.Collapsed = True
cpExt.ClientState = True
Next
Next
Catch ex As Exception
Throw ex
End Try
End Sub
I've successfully used CollapsiblePanelExtenders in a 2-level nested GridView setup that without a problem before, and without having to set clientState. However, I've had to specify clientState when using CollapsiblePanelExtenders with Repeaters before.
Does anyone have any input regarding why these extenders will not function in this 3-level nested setup?
It looks like the reason it's required is because it needs a postback to make all that logic work:
if (this.SupportsClientState) {
ScriptManager.RegisterHiddenField(this, this.ClientStateFieldID, this.SaveClientState());
this.Page.RegisterRequiresPostBack(this);
}
This is from public class ScriptControlBase in the AjaxControlToolkit space.
Are you wrapping this in an UpdatePanel? Does it cause a postback to use the CPE in the repeater? It's been awhile since I've tried to do a CPE in a repeater, and I'm not setup at this point to check the code out and build one.
Is there a reason you can't just use something completely client-side and just expand/collapse these using javascript? Are you loading data dynamically server side when these things get expanded?

Resources