set field to a value after DetailView is updated - asp.net

After the DetailsView is updated and clicked the Update Command button on the DetailView; I want to set one of the fields to “Complete”. What am I doing wrong here? Pls. help.
here is my code behind:
Protected Sub Test(sender As Object, e As System.Web.UI.WebControls.DetailsViewUpdatedEventArgs) Handles DetailsView1.ItemUpdated
If IsPostBack Then
Dim TextBox7 As TextBox = TryCast(DetailsView1.Rows(0).Cells(0).FindControl("TextBox7"), TextBox)
TextBox7.Text = "Complete"
End If
End Sub

I have used this method and got it to work.
Protected Sub PageDetailsView_ItemCommand(sender As Object, e As DetailsViewCommandEventArgs)
If Me.PageDetailsView.DefaultMode = DetailsViewMode.[ReadOnly] Then
If e.CommandName.Equals("GenerateModifiedDate", StringComparison.CurrentCultureIgnoreCase) Then
Dim modifiedDateLabel As Label = TryCast(Me.PageDetailsView.FindControl("ModifiedDateLabel"), Label)
modifiedDateLabel.Text = DateTime.Now.ToString()
End If
Else
If e.CommandName.Equals("GenerateModifiedDate", StringComparison.CurrentCultureIgnoreCase) Then
Dim modifiedDateTextbox As TextBox = TryCast(Me.PageDetailsView.FindControl("ModifiedDateTextbox"), TextBox)
modifiedDateTextbox.Text = DateTime.Now.ToString()
End If
End If
End Sub

Related

how to find the button id inside the Gridview which is in update panel?

i am not able to find the id of the update button is thee any way to
find the update button id which is inside the gridview and the grid is
inside the update panel.
Script register is written is page load. i am writing this so as
currently update button is firing on second click
ASPX code
<asp:UpdatePanel ID="UpdatePanelSubMeter" runat="server">
<ContentTemplate>
<EditItemTemplate>
<asp:Button ID="btn_Update" Style="background-color: #B2DE94; width: 40px" CausesValidation="false" runat="server" OnClientClick="return fnCheck(this);" Text="Update" CommandName="Update" />
</EditItemTemplate>
</asp:UpdatePanel>
vb.net code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.ErrorLabel.Text = String.Empty
Me.ErrorLabel.Visible = False
Dim pageName = HttpContext.Current.Request.Url.AbsoluteUri
If (Not Page.IsPostBack) Then
tblNAbers.Visible = True
BindBLDGDropDown("adonepudi")
End If
For Each gvr As GridViewRow In GridSubMeter.Rows
If gvr.RowType = DataControlRowType.DataRow Then
Dim button As Button = CType(gvr.FindControl("btn_Update"), Button)
If Not (button Is Nothing) Then
ScriptManager.GetCurrent(Me).RegisterPostBackControl(button)
end sub
Protected Sub ddlBldgId_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlBldgId.SelectedIndexChanged
If ddlBldgId.SelectedItem.Value != -1 Then
BindGridSubMeter()
end sub
Protected Sub BindGridSubMeter()
Dim conMRI As New ConnectionMRI()
Dim ds As DataSet = conMRI.NabersSubMetergetData(ddlBldgId.SelectedItem.Value, ddlRating.SelectedItem.Value)
TextExclusions.Text = ds.Tables(1).Rows(0).Item(0).ToString()
UpdatePanelExclusions.update()
With GridSubMeter
.DataSource = ds.Tables(0)
.DataBind()
End With
End Sub
Protected Sub GridSubMeter_RowEditing(sender As Object, e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridSubMeter.RowEditing
GridSubMeter.EditIndex = e.NewEditIndex
Me.BindGridSubMeter()
End Sub
Protected Sub GridSubmeter_PageIndexChanging(sender As Object, e4 As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridSubMeter.PageIndexChanging
GridSubMeter.PageIndex = e4.NewPageIndex
Me.BindGridSubMeter()
End Sub
Protected Sub GridSubMeter_RowUpdating(sender As Object, e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridSubMeter.RowUpdating
Dim txtMeterIdn As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txtMeterIdn"), TextBox)
Dim txCTFact As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txCTFact"), TextBox)
Dim txReadStartDate As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txReadStartDate"), TextBox)
Dim txReadEndDate As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txReadEndDate"), TextBox)
Dim txStartKwh As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txStartKwh"), TextBox)
Dim txEndKwh As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txEndKwh"), TextBox)
Dim txBillPer As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txBillPer"), TextBox)
Dim MeterIdn As String = txtMeterIdn.Text.Trim.ToString()
Dim CTFact As Decimal = Convert.ToDecimal(txCTFact.Text)
Dim ReadStartDate As Date = Date.Parse(txReadStartDate.Text)
Dim ReadEndDate As Date = Date.Parse(txReadEndDate.Text)
Dim StartKwh As Decimal = Convert.ToDecimal(txStartKwh.Text)
Dim EndKwh As Decimal = Convert.ToDecimal(txEndKwh.Text)
Dim billper As Decimal = Convert.ToDecimal(txBillPer.Text)
Dim leasid As String = GridSubMeter.Rows(e.RowIndex).Cells(0).Text.Trim.ToString()
Dim suitid As String = GridSubMeter.Rows(e.RowIndex).Cells(1).Text.Trim.ToString()
Dim occupant As String = GridSubMeter.Rows(e.RowIndex).Cells(2).Text.Trim.ToString()
GridSubMeter.EditIndex = -1
Dim conMRI As New ConnectionMRI()
conMRI.NaberSubmeter(ddlBldgId.SelectedItem.Value, leasid, suitid, occupant, MeterIdn, CTFact, ReadStartDate, ReadEndDate, StartKwh, EndKwh, billper)
Me.BindGridSubMeter()
End Sub
Try removing
For Each gvr As GridViewRow In GridSubMeter.Rows
If gvr.RowType = DataControlRowType.DataRow Then
Dim button As Button = CType(gvr.FindControl("btn_Update"), Button)
If Not (button Is Nothing) Then
ScriptManager.GetCurrent(Me).RegisterPostBackControl(button)
from page load and paste it in BindGridSubMeter at the end.
Try this
For Each gr As GridViewRow In Grid_Records.Rows
Dim bt As Button = DirectCast(gr.Cells(0).FindControl("btn_Update"), Button)
Dim here As bt.properties
Next

ASP VB Stuck on Dynamic Controls, Viewstate, and Postback. Could really use some help to get back on track

I've been reading posts and articles and just getting a little confused and consequently burning through time I don't have at the moment
Can someone look at my code and tell me where I've gone wrong?
Partial Class PayerContacts
Inherits System.Web.UI.Page
Dim connStrDRContacts As String = ConfigurationManager.ConnectionStrings("DRContacts_SQL").ConnectionString
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
navBuild()
End Sub
Protected Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
If IsPostBack Then
LoadContacts(ViewState("objSender"))
End If
End Sub
Private Function navBuild() As Integer
Dim SQLstrDRs As String = "SELECT * FROM DRList"
Dim DbConnDRs As SqlConnection = New SqlConnection(connStrDRContacts)
DbConnDRs.Open()
Dim dtDRsTemp As New DataTable
Dim SQLAdapterDRs As New SqlDataAdapter(SQLstrDRs, DbConnDRs)
SQLAdapterDRs.Fill(dtDRsTemp)
'Loop through each row of the DataView to create HTML table data
Dim NewTableRow As New TableRow
For Each row As DataRow In dtDRsTemp.Rows
'CREATE table with button to display contacts related to client (one to many)
Dim NewTableButton As LinkButton = New LinkButton
NewTableButton.ID = "btnDRName" & NewTableText
NewTableButton.ViewStateMode = UI.ViewStateMode.Enabled
AddHandler NewTableButton.Click, AddressOf LoadContacts
Next
Return 0
End Function
Protected Sub LoadContacts(sender As Object, e As EventArgs)
Dim LoopCount As Integer = 0
Dim SQLstrLoadTable As String = "SELECT * FROM ContactList WHERE DRVendor = '" & sender.Text.ToString & "'"
and so on....
SQLAdapterLoadTable.Fill(dtLoadTableTemp)
Dim NewTableRow As New TableRow
For Each row As DataRow In dtLoadTableTemp.Rows
'CREATE Accordion to display data
NewAccordion.ID = "ContactAccordion" & LoopCount
NewAccordion.Visible = True
blah, blah...
'SET Pane
NewAccordionPane.HeaderContainer.ID = "PaneHeader" & LoopCount
NewAccordionPane.ContentContainer.ID = "PaneContent" & LoopCount
'CREATE button to open ModalPopup to EDIT each record
Dim imgGear As New ImageButton
imgGear.ID = "btnGear" & row!ID.ToString
imgGear.ViewStateMode = UI.ViewStateMode.Enabled
AddHandler imgGear.Click, AddressOf EditRecord
'LOAD Pane
NewAccordionPane.HeaderContainer.Controls.Add(NewHeaderTable)
NewAccordionPane.ContentContainer.Controls.Add(New LiteralControl(NewTableText))
ViewState("objSender") = sender
End Sub
Protected Sub EditRecord(ByVal sender As Object, ByVal e As EventArgs)
'Open ModalPopup to edit record
popup.Show()
pnlAddEdit.Visible = True
End Sub
End Class
The Infinities Loop articles on ViewState and Dynamic Controls should really be read by every Webforms developer: -
http://mocha.mojoskins.com/SharedFiles/Download.aspx?pageid=566&mid=786&fileid=38
http://weblogs.asp.net/infinitiesloop/TRULY-Understanding-Dynamic-Controls-_2800_Part-1_2900_
The examples are in C# but you should be able to figure out what's going on, it's the same base class library after all.

ASP.NET LinkButton in GridView causing full postback

This one is REALLY driving me nuts. I've read, and tried, most of the workarounds but still it posts back!!
All the markup is generated dynamically from code-behind and inserted into a page that is part of a Master Page, from the init event.
There are a series of nested tabs, the tab content for the most part is data in a GridView. Each Gridview is set in it's own update panel. Every time a LinkButton in the GridView is clicked there is a full postback causing the tabs to reset (any button outside of the GridView and in the UpdatePanel doesn't cause a full postback.
LinkButtons are generated like this
Dim Select_Field As New CommandField
With Select_Field
.HeaderText = "View Transactions"
.SelectText = "View Transactions"
.ShowSelectButton = True
End With
GV.Columns.Add(Select_Field)
Registering with ToolKitScriptManager
Private Sub AssessmentsMain_RowDataBound(sender As Object, e As GridViewRowEventArgs)
Try
If e.Row.RowType = DataControlRowType.DataRow Then
Dim vID As Integer = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "ID"))
Dim LB As LinkButton = CType(e.Row.Cells(4).Controls(0), LinkButton)
LB.ID = "AssMain_" & vID
AjaxControlToolkit.ToolkitScriptManager.GetCurrent(Me).RegisterAsyncPostBackControl(LB)
End If
Catch ex As Exception
Dim vError As New SendError
vError.MailError("840", PageName, ex)
ShowError()
End Try
End Sub
and the generated markup for one row is like this
<tr class="GridView" style="color:#333333;background-color:#F7F6F3;">
<td>10</td>
<td>Adam White</td>
<td>4224 Res Road</td>
<td align="right">$6,850.65</td>
<td>
<a id="ctl00_ContentPlaceHolder1_AssessmentsMainGV_ctl02_AssMain_10" href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$AssessmentsMainGV','Select$0')" style="color:#333333;">View Transactions</a>
The GridView class
Public Class HAS_Gridview
Inherits GridView
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
MyBase.OnInit(e)
CellPadding = 4
GridLines = WebControls.GridLines.None
ForeColor = Drawing.ColorTranslator.FromHtml("#333333")
ClientIDMode = UI.ClientIDMode.AutoID
With MyBase.FooterStyle
.BackColor = Drawing.ColorTranslator.FromHtml("#E2DED6")
.Font.Bold = True
.ForeColor = Color.White
End With
RowStyle.BackColor = Drawing.ColorTranslator.FromHtml("#F7F6F3")
RowStyle.ForeColor = Drawing.ColorTranslator.FromHtml("#333333")
PagerStyle.HorizontalAlign = WebControls.HorizontalAlign.Center
PagerStyle.ForeColor = Color.Black
PagerStyle.BackColor = Drawing.ColorTranslator.FromHtml("#E2DED6")
With MyBase.SelectedRowStyle
.BackColor = Drawing.ColorTranslator.FromHtml("#E2DED6")
.Font.Bold = True
.ForeColor = Drawing.ColorTranslator.FromHtml("#333333")
End With
With MyBase.HeaderStyle
.BackColor = Drawing.ColorTranslator.FromHtml("#E2DED6")
.Font.Bold = True
.ForeColor = Color.Black
.CssClass = "GridView"
End With
EditRowStyle.BackColor = Drawing.ColorTranslator.FromHtml("#999999")
With MyBase.AlternatingRowStyle
.BackColor = Color.White
.ForeColor = Drawing.ColorTranslator.FromHtml("#284775")
.CssClass = "GridView"
End With
With MyBase.RowStyle
.CssClass = "GridView"
End With
End Sub
End Class
Have you tried adding trigger programmatically instead of registering in AjaxControlToolkit:
Dim trigger As New AsyncPostBackTrigger()
trigger.ControlID = LB.ID
trigger.EventName = "Click"
MyUpdatePanel.Triggers.Add(trigger)
It looks like the postback is caused by href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$AssessmentsMainGV','Select$0')" in the generated markup for the anchor tag.
Try to define your own _doPostBack.
If you haven't checked post a and post b already, they offer a couple of ways to do that.
In the end the only way I could get this to work was
Create a class for a LinkButton Template
Public Class LinkButtonTemplate
Implements ITemplate
Private m_ColumnName As String
Event LinkButtonItem_Clicked(sender As LinkButton, e As EventArgs)
Public Property ColumnName() As String
Get
Return m_ColumnName
End Get
Set(ByVal value As String)
m_ColumnName = value
End Set
End Property
Public Sub New()
End Sub
Public Sub New(ByVal ColumnName As String)
Me.ColumnName = ColumnName
End Sub
Public Sub InstantiateIn(container As Control) Implements ITemplate.InstantiateIn
Dim LB As New LinkButton()
With LB
.ID = "LB_" & ColumnName
.Text = ColumnName
.OnClientClick = "LinkButtonClick(this);"
End With
container.Controls.Add(LB)
End Sub
End Class
Add this javascript so that it would post the ID to a hidden field and click a hidden button
Private Sub LoadLinkButtonClick()
Try
Dim SB As New StringBuilder
SB.Append("function LinkButtonClick(LinkButton){ ")
SB.Append("setTimeout(function() { ")
SB.Append("$get('" & GridViewLBClicked.ClientID & "').click(); ")
SB.Append(" }, 300); ")
SB.Append("var sendingID = LinkButton.id; ")
SB.Append("document.getElementById('" & HiddenField1.ClientID & "').value = sendingID; ")
SB.Append("} ")
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "LoadLinkButton", SB.ToString, True)
Catch ex As Exception
Dim vError As New SendError
vError.MailError("1229", PageName, ex)
End Try
End Sub
On the RowDataBound event capture the ID we need and add it to the LinkButton ID (so now we know both the sending GridView and the selected row)
Private Sub AssessmentsMain_RowDataBound(sender As Object, e As GridViewRowEventArgs)
Try
If e.Row.RowType = DataControlRowType.DataRow Then
Dim vID As Integer = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "ID"))
Dim LB As LinkButton = CType(e.Row.Cells(4).Controls(0), LinkButton)
LB.ID = "AssMain_" & vID
End If
Catch ex As Exception
Dim vError As New SendError
vError.MailError("840", PageName, ex)
ShowError()
End Try
End Sub
From the hidden button click we can recover all the data we need to make the async postback
Private Sub RaiseLinkButton_Click(sender As Object, e As EventArgs)
Try
Dim vFunction As New Functions
Dim vValue As String = HiddenField1.Value
Dim vSplit = vValue.Split("_")
Dim i As Integer = 0
For Count As Integer = 0 To vSplit.Length - 1
i += 1
Next
Dim DGName As String = vSplit(i - 2)
Select Case DGName
Case "AssMain"
Dim MV As MultiView = vFunction.FindControlRecursive(BodyMain, "AssessmentMultiView")
Dim GV As CustomControl.HAS_Gridview = vFunction.FindControlRecursive(BodyMain, "AssessmentDetailGV")
With GV
.DataSource = AssessmentsDetail_ReturnDataSet()
.DataBind()
.PageIndex = 0
End With
MV.ActiveViewIndex = 1
Dim vPanel As UpdatePanel = vFunction.FindControlRecursive(BodyMain, "AssessmentUpdatePanel")
vPanel.Update()
End Select
Catch ex As Exception
Dim vError As New SendError
vError.MailError("953", PageName, ex)
ShowError()
End Try
End Sub

How to get the ID of a editing textbox in gridview

I want to get the ID of a textbox like below to add validator, the Client ID contains generated string, UniqueID too, but only the ID contains nothing, why?
Protected Sub GridView1_RowDataBound(ByVal sender As GridView, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
'Manipulate only editing row.
If e.Row.RowType = DataControlRowType.DataRow Then
If sender.EditIndex = e.Row.RowIndex Then
'Search textbox and add validators.
For Each cell As TableCell In e.Row.Cells
If cell.Controls.Count = 1 AndAlso TypeOf (cell.Controls(0)) Is TextBox Then
Dim txt As TextBox = DirectCast(cell.Controls(0), System.Web.UI.WebControls.TextBox)
'txt.ID is nothing...why?
SetValidators(cell.Controls, txt.ID)
End If
Next
End If
End If
End Sub
Well here is a workaround if applies to your application ,
Dim txt As TextBox = DirectCast(cell.Controls(0), System.Web.UI.WebControls.TextBox)
//'txt.ID is nothing...why?
// Here you can assign new ID to your control as per your logic
txt.ID = "newID";
SetValidators(cell.Controls, txt.ID)
You can try following code to assign the validator control to the gridview control.
I am not sure what your doing with SetValidators()function.
Protected Sub GridView1_RowDataBound(ByVal sender As GridView, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
'Manipulate only editing row.
If e.Row.RowType = DataControlRowType.DataRow Then
If sender.EditIndex = e.Row.RowIndex Then
'Search textbox and add validators.
For Each cell As TableCell In e.Row.Cells
If cell.Controls.Count = 1 AndAlso TypeOf (cell.Controls(0)) Is TextBox Then
Dim txt As TextBox = DirectCast(cell.Controls(0), System.Web.UI.WebControls.TextBox)
'txt.ID is nothing...why?
SetValidators(cell.Controls, txt.ClientID)
End If
Next
End If
End If
End Sub
Finally, I'v solved that problem by to apply the workaround below.
Dim txt As TextBox = DirectCast(cell.Controls(0), System.Web.UI.WebControls.TextBox)
'The ID is generated by to refer ClientID.
Dim foo = txt.ClientID
'Therefore, already txt.ID is not nothing.
SetValidators(cell.Controls, txt.ID)
Thank you for your cooperation.

viewState value is not shown after first postback

I'm new to asp.net (after programming for years in classic asp). I'm trying to build a page which adds something to a string.
My code is following:
default.aspx
<body>
<form id="form1" runat="server">
<div>
<p><asp:textbox id="tb" runat="server"></asp:textbox></p>
<asp:Panel ID="tbPanel" runat="server"></asp:Panel>
</div>
</form>
</body>
Code behind:
Partial Class demo_Default
Inherits System.Web.UI.Page
Public Property gesStr As String
Set(value As String)
ViewState("gesStr") = value
End Set
Get
Dim o As Object = ViewState("gesStr")
If o Is Nothing Then
Return ""
Else
Return o
End If
End Get
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim anzeigeStr As String = ""
If Page.IsPostBack Then
Else
gesStr = "1;"
End If
tb.Text = gesStr
Dim iButton As New Button
iButton.Text = "add"
iButton.CommandArgument = "1;"
AddHandler iButton.Click, AddressOf add
tbPanel.Controls.Add(iButton)
Me.anzeige()
End Sub
Private Sub add(ByVal sender As Object, ByVal e As EventArgs)
Dim myButton As Button = DirectCast(sender, Button)
Dim addString As String = myButton.CommandArgument
gesStr += addString
End Sub
Private Sub anzeige()
Dim gesArray As Array = Split(gesStr, ";")
For xLauf As Integer = 0 To UBound(gesArray) - 1
Dim anzLabel As New Label
anzLabel.Text = "<p>" & gesArray(xLauf) & "</p>"
tbPanel.Controls.Add(anzLabel)
Next
End Sub
End Class
The problem:
Pressing the button will cause a postBack, but the result of adding won't appear until the button is pressed a second time. The desired result is that the sub displays the correct array within the loop after the first time pressing the button.
Thank you so much for any help!
You need to call the function anzeige() and bind gesStr value to the textbox control each time the button is click. See the code below:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
Else
gesStr = "1;"
End If
tb.Text = gesStr
Dim iButton As New Button
iButton.Text = "add"
iButton.CommandArgument = "1;"
iButton.CommandName = "1;"
AddHandler iButton.Click, AddressOf add
tbPanel.Controls.Add(iButton)
End Sub
Private Sub add(ByVal sender As Object, ByVal e As EventArgs)
Dim myButton As Button = DirectCast(sender, Button)
Dim addString As String = myButton.CommandArgument
gesStr += addString
anzeige()
End Sub
Private Sub anzeige()
Dim gesArray As Array = Split(gesStr, ";")
For xLauf As Integer = 0 To UBound(gesArray) - 1
Dim anzLabel As New Label
anzLabel.Text = "<p>" & gesArray(xLauf) & "</p>"
tbPanel.Controls.Add(anzLabel)
Next
'Bind gesStr value to the textbox control
tb.Text = gesStr
End Sub

Resources