I'm working on a custom GridView control and need some help. I can get it to properly spit out what I need if I manually put in the column name. Right now I have 2 problems. The first one is getting the column headers to display dynamically. The second is filling in row items dynamicly.
Default.aspx
<asp:View id="vCreateNew" runat="server">
Content Here (View 2)...
<trac:DataGridView id="gvMain" runat="server" GridLines="Horizontal" AutoGenerateColumns="False" > </trac:DataGridView>
</asp:View>
Default.aspx.vb
Partial Class processes_ProgramTrack_Default
Inherits Citi.CSPaper.Controls.BasePage
Protected Sub ProgramTrackNav_MenuItemClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MenuEventArgs) Handles ProgramTrackNav.MenuItemClick
Dim strSelection As String = ProgramTrackNav.SelectedValue
Dim sqlDataSource As New SqlDataSource()
sqlDataSource.ConnectionString = ConfigurationManager.ConnectionStrings("CSPaperWEBConnectionString").ConnectionString
Select Case strSelection
......
Case "CreateNew"
mlvNav.SetActiveView(vCreateNew)
sqlDataSource.SelectCommand = "SELECT [ProgramNumber], [ProgramName], [ProgramStatus] FROM tblPrgTrackPrograms"
Dim args As New DataSourceSelectArguments
gvMain.DataSource = sqlDataSource.Select(args)
gvMain.DataBind()
........
End Select
End Sub
End Class
GridViewControl.ascx
<%# Control Language="VB" AutoEventWireup="false" CodeFile="GridViewControl.ascx.vb" Inherits="GridViewControl" %>
<asp:GridView ID="GridViewControl" runat="server" >
</asp:GridView>
GridViewControl.ascx.vb
Public Class GridViewControl
Inherits System.Web.UI.UserControl
Private _html As New StringBuilder()
Private _dataSource As IEnumerable
Private _CssClass As String
Private _CellSpacing As String
Public Property DataSource() As IEnumerable
Get
Return _dataSource
End Get
Set(ByVal value As IEnumerable)
_dataSource = value
End Set
End Property
Public Overridable Property CssClass() As String
Get
Return _CssClass
End Get
Set(ByVal value As String)
_CssClass = value
End Set
End Property
Public Overridable Property CellSpacing() As String
Get
Return _CellSpacing
End Get
Set(ByVal value As String)
_CellSpacing = value
End Set
End Property
Private Sub CreateBulletedList()
Dim dataSource As IEnumerable = Nothing
Dim i As Integer = 0
Dim strArr() As String = {"ID", "Name", "Fee"}
Try
dataSource = Me._dataSource
Catch
End Try
If Not (dataSource Is Nothing) Then
_html.Append("<table id=""" & ClientID & """ class=""" & _CssClass & """ CellSpacing=""" & _CellSpacing & """>")
_html.Append("<thead>" & vbCrLf & "<tr>" & vbCrLf)
For Each Item As String In strArr
_html.Append("<th>" & Item & "</th>" & vbCrLf)
Next
_html.Append("</tr>" & vbCrLf & "</thead><tbody>" & vbCrLf)
For Each dataObject As Object In dataSource
_html.Append("<tr>" & vbCrLf)
For i = 0 To 2
_html.Append("<td>" & vbCrLf)
_html.Append(dataObject.Row(i))
_html.Append("</td>" & vbCrLf)
Next
_html.Append("</tr>" & vbCrLf)
Next dataObject
_html.Append("</tbody></table>" & vbCrLf)
End If
End Sub
Public Overrides Sub DataBind()
MyBase.OnDataBinding(EventArgs.Empty)
CreateBulletedList()
End Sub
Protected Overrides Sub Render(ByVal output As HtmlTextWriter)
output.Write(_html)
End Sub
End Class
------------------------------------
| Table Data |
------------------------------------
ID AppName Environment
2 TestApp UAT
3 ServerFileMaint UAT
4 ProgramTrack Development
5 RegZ_Stmnt_Adj Active
6 SecInv Decommission
I do not want to manually code for i = 0 to ..., the upperbound, but want to do this dynamicly. Same way for the headings. The problem I run into is if I don't hard code the upperbound I get an error message stating Cannot find column 3.. I get this when coding a second For Each block to loop through the row contained data.
I think I understand whats going on here, and how to fix it.
The biggest source of confusion for me is this block:
For Each dataObject As Object In dataSource
_html.Append("<tr>" & vbCrLf)
For i = 0 To 2
_html.Append("<td>" & vbCrLf)
_html.Append(dataObject.Row(i))
_html.Append("</td>" & vbCrLf)
Next
_html.Append("</tr>" & vbCrLf)
Next dataObject
If dataSource is a DataSet then this kind of makes sense... but not really because instead you would want to reference Table(0). If dataSource is a DataTable then this kind of makes sense except not really because then you would want to loop through For Each dataObject as DataRow in dataSource.Rows. This doesn't appear to be the case though because you reference dataObject.Row(i).
What you probalby want to do is (in rough/untested code) more like this:
For Each dataObject As DataRow In dataSource.Rows
_html.Append("<tr>" & vbCrLf)
For Each col as DataColumn In dataSource.Columns
_html.Append("<td>" & vbCrLf)
_html.Append(dataObject(col).ToString())
_html.Append("</td>" & vbCrLf)
Next
_html.Append("</tr>" & vbCrLf)
Next
This makes the assumption that dataSource is a DataTable, you are going to loop through all of that tables rows, and then for each row you will loop through all columns in the datatable and get the data in that row for each column and display it.
Related
I created a tcp connection in vb6 to grab the weight off of a scale and display that weight after pressing a button. The problem is that the weight is not displayed until the SECOND (2nd) click of the button, not the first. I have set a break point in various spots and upon the first click of the button, it takes me to that break point, so I know the event is firing as it should, but nothing is displayed until the 2nd click. I have done a bunch of research but can't seem to find anyone with the exact problem (or solution).
Public tcpC As New Winsock
'Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Sub CFixPicture_Close()
tcpC.Close
End Sub
Private Sub CFixPicture_Initialize()
tcpC.LocalPort = 0
tcpC.Connect "192.168.0.1", 8000
End Sub
Private Sub CommandButton1_click()
On Error GoTo errHandler
Dim strData As String
tcpC.SendData "S" & vbCrLf
tcpC.GetData strData
Text1.Caption = "Weight: " & strData
Exit Sub
errHandler:
MsgBox "error:" & Err.Description
End Sub
I am making an assumption that your code is in the form and you are just declaring a new object of type Winsock. My code declares a Winsock variable using the keyword WithEvents to get access to the events raised by the Winsock object. The particular event you're interested in is DataArrival. It is fired by the Winsock control when data is received. I moved setting the text to this event. Also, you cannot use WithEvents and "As New" (you really don't want to use As New anyway), so I create the object before I set the properties in the CFixPicture_Initialize() method. Finally, I added setting the object to nothing after closing it.
Option Explicit
Private WithEvents tcpC As Winsock
Private Sub CFixPicture_Close()
tcpC.Close
Set tcpP = Nothing
End Sub
Private Sub CFixPicture_Initialize()
Set tcpC = New Winsock
tcpC.LocalPort = 0
tcpC.Connect "192.168.0.1", 8000
End Sub
Private Sub CommandButton1_click()
On Error GoTo errHandler
Dim strData As String
tcpC.SendData "S" & vbCrLf
'there is no data here yet - moved to the DataArrival event
'tcpC.GetData strData
'Text1.Caption = "Weight: " & strData
Exit Sub
errHandler:
MsgBox "error:" & Err.Description
End Sub
Private Sub tcpC_DataArrival(ByVal bytesTotal As Long)
Dim strData As String
tcpC.GetData strData
Text1.Caption = "Weight: " & strData
End Sub
I am basically creating textboxes dynamically for adding a test to the database. The number of textboxes to be created was passed as a query string from the web page before. Here is the code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim NoOfQuestions As Integer = Request.QueryString("NoOfQuestions")
Dim txtboxQ(NoOfQuestions - 1) As TextBox
Dim txtboxA(NoOfQuestions - 1) As TextBox
For i = 1 To NoOfQuestions
Placeholder.Controls.Add(New LiteralControl("<span>Question " & i & "</span>"))
Placeholder.Controls.Add(txtboxQ(i - 1))
Placeholder.Controls.Add(New LiteralControl("</br>"))
Placeholder.Controls.Add(New LiteralControl("<span>Correct Answer</span>"))
Placeholder.Controls.Add(txtboxA(i - 1))
Placeholder.Controls.Add(New LiteralControl("</br>"))
Next
End Sub
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
'Some SQL stuff
Response.Redirect("HomePage.aspx")
End Sub
I am trying to pass both the textbox arrays that were declared in Page_Load to the other sub btnSubmit_Click. I tried to pass it as parameter like this but it didn't seem to work:
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs, ByRef txtboxQ() As TextBox, ByRef txtboxA As TextBox) Handles btnSubmit.Click
'Some SQL stuff
Response.Redirect("HomePage.aspx")
End Sub
Quiet lost here, thanks for your help!
You can pass the textboxes content as output parameters in the querystring, as you did with your input parameter NoOfQuestions
Dim sQuery As String
For i = 1 To NoOfQuestions
sQuery &= "Question" & i & " & txtboxQ(i - 1).Text & "Answer" & i & "=" & txtboxA(i - 1).Text
Next i
Response.Redirect("HomePage.aspx?" & sQuery)
And the parse the query string in the Page Load event of HomePage.aspx. You can also pass the values as session variables
Session("Question1") = txtboxQ(i - 1).Text
...
And then
Dim question1 As String = Session("Question1")
....
Declare a list of text boxes on page level
Public textQ = New List(Of TextBox)
Public textA = New List(Of TextBox)
Change your code to following
For i = 1 To NoOfQuestions
Placeholder.Controls.Add(New LiteralControl("<span>Question " & i & "</span>"))
Dim txtboxq = New TextBox()
txtboxq.ID = "txtq_" & i
Placeholder.Controls.Add(txtboxq)
textQ.Add(txtboxq)
Placeholder.Controls.Add(New LiteralControl("</br>"))
Placeholder.Controls.Add(New LiteralControl("<span>Correct Answer</span>"))
Dim txtboxa = New TextBox()
txtboxa.ID = "txta_" & i
Placeholder.Controls.Add(txtboxa)
textA.Add(txtboxa)
Placeholder.Controls.Add(txtboxa)
Placeholder.Controls.Add(New LiteralControl("</br>"))
Next
then access the values in the list for any purpose, may be print values on submit or whatever..
eg:
For Each tb As TextBox In Me.textQ
Me.label1.Text = Me.label1.Text & tb.Text.Trim()
Next
Wondering why would you want to pass the variables like that when you can declare the variables in page level and access it from any method/function. Any special requirement?
what you are trying to do here is unclear as well.
You can use global variable inside you class, and place it below your class code. And if you want to use it, you just call that global variable.
I have a gridview which is going to be used to update a mysqldatabase, I only want to update 1 field,
It all works apart from getting the data from the input textbox on the gridview.
in the code below, strdocumentnumber = 77500 I want 77500 to come from the drawing No. column field of the updating row in the gridview and the value that i want to update is strAccess_Code also to come from the gridview Code column.
It all works if hard coding the values.
Private Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating
'' do update..
Dim strdocumentNumber As String = 77500
Dim strAccess_Code As String = 8
dbConn = New MySqlConnection("Data Source=localhost;password=****;user id=root;database=drawlib;")
sql = "UPDATE core " & vbCrLf & _
"SET F6 ='" & strAccess_Code & "'" & vbCrLf & _
"WHERE F1 = '" & strdocumentNumber & "'"
Try
dbConn.Open()
dbcomm = New MySqlCommand(sql, dbConn)
dbread = dbcomm.ExecuteReader()
dbread.Close()
Catch myerror As MySqlException
MsgBox("Error in Saving Data: " & myerror.Message)
'dbread.Close()
Exit Sub
End Try
GridView1.EditIndex = -1
GridView1.DataSource = SqlDataSource2
GridView1.DataBind()
End Sub
thanks
I think you'll have to create a textbox in your codebehind to assign a value from your gridview textbox:
Edit
You may need to find the proper row before pulling the value from the textbox. Try this
Dim row As GridViewRow = GridView1.Rows(e.RowIndex)
If row.RowType = DataControlRowType.DataRow Then
Dim textbox As TextBox = CType(row.FindControl("nameofyourgridview textbox here"),TextBox)
strdocumentNumber = textbox.Text
End If
/Edit
In your Gridview, you'll need to change your BoundField to a TemplateField. See here for an example.
Use the designer to make the conversion (see link above) or select your column in the gridview designer and click the 'convert this column to a templatefield' button. You'll then have a textbox that you can name and grab from the code-behind.
I am new to jQuery and have some questions. I have created a server web control (it implements a webControl) and wanted to know how to refresh the control when an event fires. In other words:
I have a server control that has a drop-down list.
When the user makes a selection, I want to cause a partial post back and reload the control (to set some public properties values that can be read by the page consuming the control).
Can this be done just by using jQuery or would I still need to update the panels?
Here is my server control:
<Assembly: WebResource("com.myControls.WebControls.miniActiveDirectorySearchStyle.css", "text/css", PerformSubstitution:=True)>
Namespace com.myControls.WebControls
< _
System.Drawing.ToolboxBitmap(GetType(Button), "myControls.WebControls.ActiveDirectorySearch.bmp"), ToolboxData("<{0}:miniActiveDirectorySearch ID='miniActiveDirectorySearch{0}' runat=""server""> </{0}:miniActiveDirectorySearch>"), _ ClientCssResource("com.myControls.WebControls.miniActiveDirectorySearchStyle.css")> _
Public Class miniActiveDirectorySearch
Inherits WebControl
Public ddlValue As New TextBox
Public ddlText As New TextBox
Private tblMainLayout As HtmlTable
Private divControlContainer As New HtmlGenericControl()
Private modalExtender As New ModalPopupExtender()
Private tbSearchUser As New TextBox
''' <summary>
'''X Offset for modal dialog
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
<Description("Mouser Over Highlight Color")> Public Property mouseOverColor As String = "#9db3d9"
''' <summary>
'''X Offset for modal dialog
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
<Description("Drop Down List Width")> Public Property ddlWidth As String = "100"
Private Sub attachWebResources()
Dim styleLink As String = "<link rel='stylesheet' text='text/css' href='{0}' />"
Dim location As String = Page.ClientScript.GetWebResourceUrl(Me.[GetType](), "myControls.WebControls.miniActiveDirectorySearchStyle.css")
Dim styleInclude As New LiteralControl([String].Format(styleLink, location))
DirectCast(Page.Header, HtmlControls.HtmlHead).Controls.Add(styleInclude)
ScriptManager.RegisterClientScriptResource(Me, Me.GetType, "com.myControls.ActiveDirectory.WebControls.jquery-1.4.1.min.js")
ScriptManager.RegisterClientScriptResource(Me, Me.GetType, "com.myControls.ActiveDirectory.WebControls.miniActiveDirectorySearch.js")
End Sub
Protected Overrides Sub CreateChildControls()
createDynamicControls()
MyBase.CreateChildControls()
End Sub
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
attachWebResources()
MyBase.OnInit(e)
End Sub
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
End Sub
Private Sub createDynamicControls()
Controls.Clear()
Try
tblMainLayout = buildMaintable()
Controls.Add(tblMainLayout)
Catch ex As Exception
Throw New ApplicationException("Exception Occurred Creating Control.", ex.InnerException)
End Try
End Sub
Private Function buildMaintable() As HtmlTable
tblMainLayout = New HtmlTable
Dim divImage As New HtmlGenericControl("div")
ddlText = New TextBox
ddlValue = New TextBox
With ddlText
.ID = "ddlText"
End With
With ddlValue
.ID = "ddlValue"
End With
With divControlContainer
.ID = Me.UniqueID & "_divSearchResults"
.Attributes.Add("onClick", "hideMe(this)")
End With
With divImage
.ID = Me.UniqueID & "_ImageDiv"
End With
With tblMainLayout
.CellPadding = 0
.CellSpacing = 0
.Style.Add("border-collapse", "collapse")
Dim tr As New HtmlTableRow
With tr
Dim td As New HtmlTableCell
With td
With tbSearchUser
.ID = Me.UniqueID & "_tbSearchName"
.Attributes.Add("onKeyPress", "searchKeyPress(event, this.id, '" & divControlContainer.UniqueID & "', '" & mouseOverColor & "','" & ddlText.ID & "','" & ddlValue.ID & "')")
.Attributes.Add("onmouseover", "document.getElementById('" & divImage.ID & "').className='DivSearchMouseOverMini', tbMouseOver(this)")
.Attributes.Add("OnmouseOut", "document.getElementById('" & divImage.ID & "').className='divSearchDefaultMini',tbMouseOut(this)")
.Width = ddlWidth
.Attributes.Add("onClick", "showSearchResults('" & divControlContainer.UniqueID & "')")
.CssClass = "tbSearchDefault"
End With
.Controls.Add(tbSearchUser)
.Controls.Add(ddlText)
.Controls.Add(ddlValue)
End With
.Controls.Add(td)
td = New HtmlTableCell
With td
With divImage
.Attributes.Add("class", "divSearchDefaultMini")
.Attributes.Add("onmouseover", "this.className='DivSearchMouseOverMini',document.getElementById('" & tbSearchUser.ID & "').className='tbSearchMouseOver'")
.Attributes.Add("onmouseout", "this.className='divSearchDefaultMini', document.getElementById('" & tbSearchUser.ID & "').className='tbSearchDefault'")
.Attributes.Add("onClick", "showSearchResults('" & divControlContainer.UniqueID & "')")
End With
.Controls.Add(divImage)
End With
.Controls.Add(td)
End With
.Controls.Add(tr)
tr = New HtmlTableRow
With tr
Dim td As New HtmlTableCell
With td
.ColSpan = 2
.Controls.Add(divControlContainer)
End With
.Controls.Add(td)
End With
.Controls.Add(tr)
End With
Return tblMainLayout
End Function
End Class
This code creates a server control with a textbox and styles to mimick a dropdown list. This way, I can add some functionality to the drop down list. I would like to cause a partial post back when the user makes a change to the "dropdown list" or textbox. All my jQuery is done in another file that is added as a web resource.
Why not use an ajax call to the server page, which won't cause an actual post-back. Grab what you need and update it on the client in the response. Or, you can fire your server code to do that as well.
jQuery ajax is really easy to use. Just declare a static Webmethod on the server to handle whatever your request is supposed to accomplish.
I have following code in page load
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
GetDetails()
PopulateRepeater()
End If
End Sub
Sub PopulateRepeater()
Dim dt As DataTable = GetDetails()
Dim dtDoc As DataTable = objdoc.GetDocDetails(Session("RegID"))
If dtDoc.Rows.Count > 0 Then
Dim strUserName As String = dt.Rows(0)("Name")
Dim files As IList(Of FileInfo) = New List(Of FileInfo)()
Dim filters As String = "*.jpg;*.png;*.gif"
For Each filter As String In filters.Split(";"c)
Dim fit As FileInfo() = New DirectoryInfo(Me.Server.MapPath("../SiteImages/" & strUserName & "/" & Session("RegID") & "/")).GetFiles(filter)
For Each fi As FileInfo In fit
files.Add(fi)
Next
Next
strPath = Server.MapPath("../SiteImages/" & strUserName & "/" & Session("RegID") & "/")
Me.Repeater1.DataSource = files
Me.Repeater1.DataBind()
End If
End Sub
I have following code in itemdatabound
Dim ThViewr As Bright.WebControls.ThumbViewer = DirectCast(e.Item.FindControl("Th1"), Bright.WebControls.ThumbViewer)
Dim dtUser As DataTable = GetDetails()
Dim dtDoc As DataTable = objdoc.GetDocDetails(Session("RegID"))
Dim strUserName As String = dtUser.Rows(0)("Name")
If dtDoc.Rows.Count > 0 Then
For i As Integer = 0 To dtDoc.Rows.Count - 1
Dim ImagePath As String = "../SiteImages/" & strUserName & "/" & Session("RegID") & "/" + dtDoc.Rows(i)("ImageName")
ThViewr.ImageUrl = ImagePath
Next
End If
My aspx contains
<div style="clear:both;">
<asp:Repeater ID="Repeater1" runat="server" >
<ItemTemplate>
<span style="padding:2px 10px 2px 10px">
<bri:ThumbViewer Id="Th1" runat="server" Height="100px" Width="100px"/>
</span>
</ItemTemplate>
</asp:Repeater>
</div>
If the imagePath ="../SiteImages/Ram/PR/First.jpg" Means the folder PR aontains exactly 3 images namely First.jpg,Second.jpg and Third.jpg.
Now with above code three images are coming but Third.jpg is repeating 3 times.First.jpg and Second.jpg is not coming.Can anybody help to resolve this.
The ItemDataBound event is raised once for every object in the bound list, so it will be fired three times in your case; once for each file. You should not loop over your data table, but rather grab the current item from the event args.
Update: looking closer at the code I find it somewhat confusing. You bind a list of FileInfo objects to the repeater, but fetch data from a DataTable when the items are bound. I am guessing that you want to show the files found, and I think that the following code in ItemDataBound will do that for you:
Dim ThViewr As Bright.WebControls.ThumbViewer = DirectCast(e.Item.FindControl("Th1"), Bright.WebControls.ThumbViewer)
Dim dtUser As DataTable = GetDetails()
Dim strUserName As String = dtUser.Rows(0)("Name")
Dim ImagePath As String = "../SiteImages/" & strUserName & "/" & Session("RegID") & "/" + DirectCast(e.Item.DataItem, FileInfo).Name
ThViewr.ImageUrl = ImagePath