Unable to read the text from a TextBox` within a `Repeater` - asp.net

I am not getting any errors but I am unable to get the value from a TextBox.
This is my VB code for reading the TextBox value:
Private Sub btn_Save_Click(sender As Object, e As EventArgs) Handlesbtn_Save.Click
For Each item As RepeaterItem In Article_Block_Migrated.Items
Dim txtField As Label = item.FindControl("Article_Number")
Dim a = txtField.Text
Dim txtField1 As TextBox = DirectCast(item.FindControl("txt_DWPDate"), TextBox)
Dim b = txtField1.Text
Next
End Sub
This is my ASP code for the Repeater:
<asp:Repeater ID="Article_Block_Migrated" runat="server">
<ItemTemplate>
<asp:TextBox Width="80px" ID="txt_DWPDate" runat="server" MaxLength="50"></asp:TextBox>
</ItemTemplate>
</asp:Repeater>

Related

Editing a row in a gridview by the use of the click into button event

I have this gridview in my application :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="True">
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:Button ID="Savebtn" runat="server" Text="تحديث البيانات" OnClick="gv_RowEditing"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="السعر الأقصى">
<ItemTemplate>
<asp:TextBox ID="mintxt" runat="server" Text='<%#Eval("prix max")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="السعر الأدنى" >
<ItemTemplate>
<asp:TextBox ID="maxtxt" runat="server" Text='<%#Eval("prix min")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Datvente" HeaderText="التاريخ" SortExpression="Datvente" />
<asp:BoundField DataField="NomAdh" HeaderText="الإسم و اللقب" SortExpression="NomAdh" />
<asp:BoundField DataField="CodAdh" HeaderText="المنخرط" SortExpression="CodAdh" />
<asp:TemplateField >
<ItemTemplate>
<asp:HiddenField ID="Ref" runat="server" Value='<%#Eval("Ref")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The event of the click into button :
Protected Sub gv_RowEditing(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim min As Double = Double.Parse(GridView1.SelectedRow.Cells("mintxt").ToString())
Dim max As Double = Double.Parse(GridView1.SelectedRow.Cells("maxtxt").ToString())
Dim reference As String = Double.Parse(GridView1.SelectedRow.Cells("Ref").ToString())
If min > max Then
avis2.Text = "الصيغة خاطئة"
Return
End If
DataAccessLayer.updatetraitementprix(min, max, reference)
avis2.Text = ""
FillingGrid(Session("region"), Session("date"), Session("speculation"))
Catch ex As Exception
avis2.Text = "الصيغة خاطئة"
GridView1.Visible = True
Return
End Try
Me.FillingGrid(Session("region"), Session("date"), Session("speculation"))
End Sub
I need to get the value of the column Ref and the new values of fields maxtxt and mintxt . but it didn't work
What are the reasons of this problem?
How can i resolve it?
There is absolutely need of RowEditing event. What you are doing is firing a simple OnClick event. So make these changes.
Markup ( Name change so that you may not confuse it with RowEditing event )
<asp:TemplateField >
<ItemTemplate>
<asp:Button ID="Savebtn" runat="server"
Text="تحديث البيانات"
OnClick="Savebtn_Click" />
</ItemTemplate>
</asp:TemplateField>
Code-behind
Protected Sub Savebtn_Click(sender As Object, e As System.EventArgs)
Dim btn As Button = CType(sender, Button)
Dim clickedRow As GridViewRow = CType(btn.NamingContainer, GridViewRow)
Dim minTextBox As TextBox = CType(clickedRow.FindControl("mintxt"), TextBox)
Dim maxTextBox As TextBox = CType(clickedRow.FindControl("maxtxt"), TextBox)
Dim refHidden As HiddenField = CType(clickedRow.FindControl("Ref"), HiddenField)
Dim min As Double = Double.Parse(minTextBox.Text)
Dim max As Double = Double.Parse(maxTextBox.Text)
Dim reference As Double = Double.Parse(refHidden.Value)
'rest of the code goes here
End Sub
Since the TextBox controls are inside of TemplateField's, you have to use Control#FindControl method to find them. Be aware of the Cell's index for each control.
Dim tbMin As TextBox = CType(GridView1.SelectedRow.Cells(1).FindControl("mintxt"), TextBox)
Dim min As Double = Double.Parse(tbMin.Text)
The reason you're getting this error is actually because the selectedrow is nothing, so you first need to get the current selected row then access all the controls in that row.
Please replace your code to the following:
Protected Sub gv_RowEditing(ByVal sender As Object, ByVal e As EventArgs)
Try
'First, get the saveBtn
Dim saveBtn As Button = DirectCast(sender, Button)
'Next, get the selected row of that button
Dim selectedRow As GridViewRow = DirectCast(saveBtn.Parent.Parent, GridViewRow)
'Now you can access all the controls of that row
Dim mintxt As TextBox = DirectCast(selectedRow.FindControl("mintxt"), TextBox)
Dim maxtxt As TextBox = DirectCast(selectedRow.FindControl("mintxt"), TextBox)
Dim Ref As HiddenField = DirectCast(selectedRow.FindControl("Ref"), HiddenField)
'Get the values of the controls
Dim min As Double = Double.Parse(mintxt.Text)
Dim max As Double = Double.Parse(maxtxt.Text)
Dim refVal As Double = Double.Parse(Ref.Value)
If min > max Then
avis2.Text = "الصيغة خاطئة"
Return
End If
DataAccessLayer.updatetraitementprix(min, max, refVal)
avis2.Text = ""
FillingGrid(Session("region"), Session("date"), Session("speculation"))
Catch ex As Exception
avis2.Text = "الصيغة خاطئة"
GridView1.Visible = True
Return
End Try
Me.FillingGrid(Session("region"), Session("date"), Session("speculation"))
End Sub

How do I grab the value of hidden field on gridview?

This is really frustrating right now.
I have this hidden field on gridview markup:
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="dhide" Value='<%# Eval("shipDates","{0:M/dd/yyyy}") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
Then on codebehind, I am trying to retrieve the value of dhide:
Sub cancelIt_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim objConnection As SqlConnection
Dim DLdates As HiddenField = DirectCast(GridView1.FindControl("dhide"), HiddenField)
Response.write (DLdates)
What am I doing wrong?
The NamingContainer of it is not the GridView but the GridViewRow where it sits.
So:
For Each row As GridViewRow In GridView1.Rows
Dim dhide = DirectCast(row.FindControl("dhide"), HiddenField)
Dim shipDates = Date.ParseExact(dhide.Value, "M/dd/yyyy", Nothing)
' ...
Next

Find the right value of textbox

I have a problem with inserting data inserting data into database.
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<!-- Some other data (text...) -->
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("PostId") %>' />
<asp:TextBox ID="txtAddComment" runat="server" CssClass="textbox" Width="200px" />
<asp:Button ID="btnAddComment" runat="server" CssClass="button" Text="Comment" CausesValidation="false" OnClick="btnAddComment_Click"/>
</ItemTemplate>
</asp:Repeater>
Code behind:
Protected Sub btnAddComment_Click(sender As Object, e As EventArgs)
Dim HiddenField1 As HiddenField = DirectCast(Repeater1.Items(0).FindControl("HiddenField1"), HiddenField)
Dim txtAddComment As TextBox = DirectCast(Repeater1.Items(0).FindControl("txtAddComment"), TextBox)
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString.ToString)
Try
If txtAddComment.Text = "" Then
Exit Sub
Else
conn.Open()
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = "INSERT INTO Comments (PostId, UserName, CommentText) VALUES (#PostId, #UserName, #Text)"
cmd.Parameters.Add("PostId", System.Data.SqlDbType.Int).Value = CInt(HiddenField1.Value)
cmd.Parameters.Add("UserName", System.Data.SqlDbType.NVarChar).Value = Context.User.Identity.Name
cmd.Parameters.Add("Text", System.Data.SqlDbType.NText).Value = MakeLink(HtmlRemoval.StripTagsCharArray(txtAddComment.Text))
cmd.ExecuteNonQuery()
End If
Catch ex As SqlException
Finally
conn.Close()
End Try
End Sub
I display some text, under the text there is textbox and button for comments. I am bounding textId in hiddenfield for inserting comments. The code works fine, but I can only add comment for the first row in database displayed by repeater. When I want to add comment for other rows (2, 3...), the page refreshes and the text in the TextBox stay there.
It is problem with this line of code:
Dim txtAddComment As TextBox = DirectCast(Repeater1.Items(0).FindControl("txtAddComment"), TextBox)
The ID from HiddenField is right. But the code doesn't perform because the line above references for the first textbox on the page and his value is null.
When I change the line of code like this:
Dim txtAddComment As TextBox = DirectCast(Repeater1.FindControl("txtAddComment"), TextBox)
It returns an error that Object reference not set to an instance of an object.
How to get the right textbox with right value?
Thanks for the answer
cast the sender to a button that sent it, then get the textbox from the parent. Example:
Protected Sub button_click(ByVal sender As Object, ByVal e As EventArgs)
Dim myButton As button= CType(sender, button)
Dim myTextBox as TextBox = CType(myButton Parent.FindControl("buttonName"), TextBox)
end sub

Why isn't the new values pulling up when I update the GridViewRow?

So what's happening is that I click the Edit button, type the updated values and hit Update. But the code-behind gets the original values not the updated values. I can't figure out why. It's always worked before.
Markup
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
CellPadding="7" ForeColor="#333333" GridLines="None" Font-Size="Small"
ShowFooter="True" DataKeyNames="CapID">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="AllocationId">
<ItemTemplate>
<asp:Label ID="show" runat="server" Text='<%# Eval("CapID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reference Number">
<ItemTemplate>
<asp:Label ID="showRefNo" runat="server" Text='<%# Eval("RefNo") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="EditRefNo"
Text='<%# Bind("RefNo") %>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox runat="server" ID="InsertRefNo"
Text='<%# Bind("RefNo") %>'/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Resource">
<ItemTemplate>
<asp:Label ID="showResource" runat="server"
Text='<%# Eval("Resource") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="EditResource"
Text='<%# Bind("Resource") %>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox runat="server" ID="InsertResource"
Text='<%# Bind("Resource") %>'/>
</FooterTemplate>
</asp:TemplateField>
<!-- and so on... -->
</Columns>
<!-- styles etc -->
<EmptyDataTemplate>
Ref Num: <asp:TextBox ID="newRefNo" runat="server"/>
Resource: <asp:TextBox ID="newResource" runat="server"/>
Hours Allocated: <asp:TextBox ID="newHours" runat="server"/>
Week Offset: <asp:TextBox ID="newOffset" runat="server"/>
<asp:Button runat="server" ID="NewDataInsert"
CommandName="NewDataInsert" Text="Insert"/>
</EmptyDataTemplate>
</asp:GridView>
Code Behind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
If Not IsPostBack Then
GridView1_DataBind()
GridView2_DataBind()
End If
End Sub
Protected Sub GridView2_RowUpdating(ByVal sender As Object, ByVal e As
GridViewUpdateEventArgs) Handles GridView2.RowUpdating
Dim capID As Label = GridView2.Rows(e.RowIndex).Cells(0)
.FindControl("show")
Dim refNo As TextBox = GridView2.Rows(e.RowIndex).Cells(1)
.FindControl("EditRefNo")
Dim resource As TextBox =
GridView2.Rows(e.RowIndex).Cells(2).FindControl("EditResource")
Dim hours As TextBox =
GridView2.Rows(e.RowIndex).Cells(3).FindControl("EditHours")
Dim offSet As TextBox =
GridView2.Rows(e.RowIndex).Cells(4).FindControl("EditOffset")
Dim newResAlloc As DataTable = resourceInfo.loadResAllocations
Dim updateRows As DataRow() =
newResAlloc.Select("CapID = " & "'" & capID.Text & "'")
If (Not updateRows Is Nothing) And updateRows.Length > 0 Then
For Each updRow As DataRow In updateRows
updRow.BeginEdit()
updRow.Item("Refno") = refNo.Text
updRow.Item("Resource") = resource.Text
updRow.Item("Hours") = hours.Text
updRow.Item("Offset") = offSet.Text
updRow.EndEdit()
Next
End If
resourceInfo.updateResAllocations(newResAlloc)
GridView2.EditIndex = -1
GridView2_DataBind()
End Sub
This could be a million and one things. What have you checked? Have you narrowed it down?
Here's some starting points for you:
Put a breakpoint inside GridView2_RowUpdating to make sure it's being called.
Check the value of capID, or capID.Text - it shouldn't be 0.
Check that your database table contains a row where CapID equals the value of capID.Text
Put a breakpoint on updateRows to ensure that the database row is being loaded into your code.
Make sure that the updRow.EndEdit() is being hit, and that the values are populated into the row correctly.
Finally, check that the updateResAllocations is working properly. It's impossible to see from here how it works, so I can't give any advice on that.
The easiest way to fix this might be to ask whoever wrote it for some assistance.
The problem was that my RowCommand method was calling the DataBind
Wrong way:
Protected Sub GridView2_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs) Handles GridView2.RowCommand
If e.CommandName = "NewDataInsert" Then
Dim refNo As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewRefNo")
Dim resource As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewResource")
Dim hours As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewHours")
Dim offset As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewOffset")
Dim newResAlloc As DataTable = resourceInfo.loadResAllocations
Dim newAllocRow As DataRow = newResAlloc.NewRow
newAllocRow.ItemArray = New Object() {Nothing, refNo.Text, resource.Text, hours.Text, offset.Text}
newResAlloc.Rows.Add(newAllocRow)
resourceInfo.updateResAllocations(newResAlloc)
ElseIf e.CommandName = "InsertNew" Then
Dim refNo As TextBox = GridView2.FooterRow.FindControl("InsertRefNo")
Dim resource As TextBox = GridView2.FooterRow.FindControl("InsertResource")
Dim hours As TextBox = GridView2.FooterRow.FindControl("InsertHours")
Dim offset As TextBox = GridView2.FooterRow.FindControl("InsertOffset")
Dim newResAlloc As DataTable = resourceInfo.loadResAllocations
Dim newAllocRow As DataRow = newResAlloc.NewRow
newAllocRow.ItemArray = New Object() {Nothing, refNo.Text, resource.Text, hours.Text, offset.Text}
newResAlloc.Rows.Add(newAllocRow)
resourceInfo.updateResAllocations(newResAlloc)
End If
GridView2_DataBind() 'Culprit
End Sub
Right way:
Protected Sub GridView2_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs) Handles GridView2.RowCommand
If e.CommandName = "NewDataInsert" Then
Dim refNo As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewRefNo")
Dim resource As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewResource")
Dim hours As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewHours")
Dim offset As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewOffset")
Dim newResAlloc As DataTable = resourceInfo.loadResAllocations
Dim newAllocRow As DataRow = newResAlloc.NewRow
newAllocRow.ItemArray = New Object() {Nothing, refNo.Text, resource.Text, hours.Text, offset.Text}
newResAlloc.Rows.Add(newAllocRow)
resourceInfo.updateResAllocations(newResAlloc)
GridView2_DataBind() 'Only called if IF is true
ElseIf e.CommandName = "InsertNew" Then
Dim refNo As TextBox = GridView2.FooterRow.FindControl("InsertRefNo")
Dim resource As TextBox = GridView2.FooterRow.FindControl("InsertResource")
Dim hours As TextBox = GridView2.FooterRow.FindControl("InsertHours")
Dim offset As TextBox = GridView2.FooterRow.FindControl("InsertOffset")
Dim newResAlloc As DataTable = resourceInfo.loadResAllocations
Dim newAllocRow As DataRow = newResAlloc.NewRow
newAllocRow.ItemArray = New Object() {Nothing, refNo.Text, resource.Text, hours.Text, offset.Text}
newResAlloc.Rows.Add(newAllocRow)
resourceInfo.updateResAllocations(newResAlloc)
GridView2_DataBind() 'Only called if IF is true
End If
End Sub

request.querystring

how can i use request.querystring in asp.net.i have a linkbutton and this is in a repeater control.i want to play video for the corresponding link _click.i want to pass a fileID of the corresponding link to a function,how can i do this ?
<asp:Repeater ID="Repeater2" runat="server">
<ItemTemplate>
<asp:LinkButton runat="server" ID="LnkBtn"
OnClick="ButtonShowVideo_Click"><%#Eval("FileName")%>
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
Protected Sub ButtonShowVideo_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles ButtonShowVideo.Click
Repeater1.DataSource = GetSpecificVideo(**here i want to get the fileID**)
Repeater1.DataBind()
End Sub
Private Function GetSpecificVideo(ByVal i As Object) As DataTable
'pass the id of the video
Dim connectionString As String = ConfigurationManager
.ConnectionStrings("UploadConnectionString").ConnectionString
Dim adapter As New SqlDataAdapter("SELECT FileName, FileID,FilePath " +
"FROM FileM WHERE FileID = #FileID", connectionString)
adapter.SelectCommand.Parameters.Add("#FileID", SqlDbType.Int).Value =
DirectCast(i,Integer)
Dim table As New DataTable()
adapter.Fill(table)
Return table
End Function
This won't help you:
<asp:Repeater ID="Repeater2" runat="server">
<ItemTemplate>
<asp:LinkButton runat="server" ID="LnkBtn"
OnClick="ButtonShowVideo_Click"><%#Eval("FileName")%>
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
as it will not put FileName into query stirng. Rather use this method:
<asp:Repeater ID="Repeater2" runat="server">
<ItemTemplate>
<asp:LinkButton runat="server" ID="LnkBtn"
CommandArgument='<%#Eval("FileName")%>'
OnClick="ButtonShowVideo_Click"><%#Eval("FileName")%>
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
In code behind:
Protected Sub ButtonShowVideo_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles ButtonShowVideo.Click
Dim btn as LinkButton = sender as LinkButton
if(btn is not null) then
if(NOT string.IsNullOrEmpty(btn.CommandArgument)) then
dim vid as integer = Convert.ToInt32(btn.CommandArgument)
Repeater1.DataSource = GetSpecificVideo(vid)
Repeater1.DataBind()
end if
end if
End Sub
If you plan to use query string, the button click can do either of the following:
Hyperlinks to a page with the designated quertstring to identify the action/entity etc
Do a server-side redirect to the page as describe in item 1 above
So where is your issue that you find challenging?

Resources