I have my GridView populating like so:
<asp:Panel ID="pnlGrid" runat="server">
<div class="m_container" style="margin-bottom:20px;">
<asp:GridView ID="grdView" runat="server" CssClass="GridViewStyle"
AutoGenerateColumns="False" GridLines="None" Width="125%" onrowdatabound="builderGridView_RowDataBound" >
<Columns>
<asp:BoundField DataField="id" Visible="False" />
<asp:BoundField HeaderText="Info" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton name='<%#Eval("status") %>' CommandArgument='<%#Eval("id")%>' runat="server" Text='<%#Eval("status")%>' CommandName='<%#Eval("status")%>' ID="statusLink" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle CssClass="RowS" />
<EmptyDataRowStyle CssClass="EmptyS" />
<PagerStyle CssClass="PagerStyle" />
<SelectedRowStyle CssClass="SelectedS" />
<HeaderStyle CssClass="HeaderS" />
<EditRowStyle CssClass="EditRowS" />
<AlternatingRowStyle CssClass="AltRowS" />
</asp:GridView>
</div>
</asp:Panel>
</asp:Content>
And the code behind is:
Private Sub LoadData(ByRef theStatus As Integer)
Dim objConn As MySqlConnection
Dim objCmd As MySqlCommand
objConn = New MySqlConnection(strConnString)
objConn.Open()
Dim strSQL As String
strSQL = "SELECT * FROM theTable WHERE status=" & theStatus & " ORDER BY created_on, status DESC;"
Dim dtReader As MySqlDataReader
objCmd = New MySqlCommand(strSQL, objConn)
dtReader = objCmd.ExecuteReader()
grdView.DataSource = dtReader
grdView.DataBind()
dtReader.Close()
dtReader = Nothing
objConn.Close()
objConn = Nothing
End Sub
Then after the above i create a LinkButton for each row like so:
Sub builderGridView_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim lbtn As LinkButton = DirectCast(e.Row.FindControl("statusLink"), LinkButton)
e.Row.Cells(1).Text = "TEST!"
If lbtn.Text = 0 Then
Dim lb As New LinkButton()
lb.Text = "Accept"
lb.CommandName = lbtn.CommandName
lb.CommandArgument = lbtn.CommandArgument
lb.Attributes.Add("class", "nounderline")
lb.ForeColor = System.Drawing.Color.Green
lb.Font.Bold = True
lb.Font.Size = 12
lb.OnClientClick = "location.href = '/page.aspx?ID=" & pageID & "&dbid=" & lb.CommandArgument & "&ACCEPT=yes'; return false;"
e.Row.Cells(4).Controls.Add(lb)
End If
End If
End Sub
How can i get values from the database (name, address, email address, etc etc) and place it within the current row its going through?
example:
(when its looping through the rows)
e.Row.Cells(1).Text = database("FName") & "<BR />" & database("LName") & "<BR />"...etc etc
Would look like this in the first row column:
Bob
Barker
How can i grab whats currently being read from the DB?
builderGridView_RowDataBound event fill be handled for each row from the database.
e.Row.DataItem will contain the item from the database
Edit:
Better way would be
Using adap As New MySqlDataAdapter(objCmd)
Dim table As New DataTable()
adap.Fill(table)
grdView.DataSource = table;
grdview.DataBind();
Adapter will load all records to the DataTable.
Then your e.Row.DataItem will be of type DataRow
Related
I'm working on a web app using Visual Studio and VB.net. I have a grid view with textboxes. When I try to get the string from the textboxes of each row to update my database, it is empty though there is something in.
I want to know why
Here is the declaration of the textboxes in the gridview ;
<asp:TemplateField HeaderText="TpNote">
<ItemTemplate>
<asp:TextBox ID="TpTextBox" runat="server" width="50px" BorderWidth="0px"></asp:TextBox>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="CiNote">
<ItemTemplate>
<asp:TextBox ID="CiTextBox" runat="server" width="50px" BorderWidth="0px" AutoPostBack="False" CausesValidation="False" ClientIDMode="Inherit"></asp:TextBox>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="CfNote">
<ItemTemplate>
<asp:TextBox ID="CfTextBox" runat="server" width="50px" BorderWidth="0px"></asp:TextBox>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
And here is the code behind:
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim rqt1, rqt2, rqt3, rqt4 As String
con.Open()
Dim i As Integer
i = 0
Try
For Each row As GridViewRow In GridView1.Rows
Dim t As TextBox
Dim ccNote As String
t = CType(row.Cells(i).FindControl("CcTextBox"), TextBox)
ccNote = t.Text
Dim t1 As TextBox
Dim tpNote As String
t1 = CType(row.Cells(i).FindControl("TpTextBox"), TextBox)
tpNote = TextBox2.Text
Dim t2 As TextBox
Dim ciNote As String
t2 = CType(row.Cells(i).FindControl("CiTextBox"), TextBox)
ciNote = t2.Text
MsgBox(t2.Text)
Dim t3 As TextBox
Dim cfNote As String
t3 = CType(row.Cells(i).FindControl("CfTextBox"), TextBox)
cfNote = t3.Text
Dim matricule As String
Try
matricule = GridView1.Rows(i).Cells(0).Text
Catch ex As Exception
End Try
i = i + 1
rqt1 = "Update INSCRITMODULE set CcNote ='" + ccNote + "' where (INSCRITMODULE.Matricule)='" + matricule + "'"
rqt2 = "Update INSCRITMODULE set TpNote ='" + tpNote + "' where (INSCRITMODULE.Matricule)='" + matricule + "'"
rqt3 = "Update INSCRITMODULE set CiNote ='" + ciNote + "' where (INSCRITMODULE.Matricule)='" + matricule + "'"
rqt4 = "Update INSCRITMODULE set CfNote ='" + cfNote + "' where (INSCRITMODULE.Matricule)='" + matricule + "'"
Dim commande1 As New SqlCommand With {
.CommandText = rqt1,
.Connection = con
}
commande1.ExecuteNonQuery()
Dim commande2 As New SqlCommand With {
.CommandText = rqt2,
.Connection = con
}
commande2.ExecuteNonQuery()
Dim commande3 As New SqlCommand With {
.CommandText = rqt3,
.Connection = con
}
commande3.ExecuteNonQuery()
Dim commande4 As New SqlCommand With {
.CommandText = rqt4,
.Connection = con
}
commande4.ExecuteNonQuery()
Next
con.Close()
Catch ex As Exception
End Try
End Sub
Thank you
I would suggest first debug the code and try to make sure if each asp textbox value is coming to t1,t2,..... to backend and then we can figure out rest of the thing.
I would suggest,
<asp:TemplateField HeaderText="TpNote">
<ItemTemplate>
<asp:TextBox ID="TpTextBox" runat="server" width="50px"
Text ='<%#Eval("CCNote")' BorderWidth="0px"></asp:TextBox>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
similarly bind values all textboxes which you want to get value in code behind.
and then find textbox and get its value
I am trying to copy a row from a gridview to be displayed on a new page through a button in one of the columns in the gridview. I have my gridview populated from an Access database that is linked to my project. I have tried several different things, but nothing will display the row information when the project is ran. The current code I am trying from the actual dataview is:
Example 1a
<asp:GridView ID="Grid1" runat="server" Width ="90%" AutoGenerateColumns="false" OnRowDeleting="Grid1_RowDeleting" DataKeyNames="Title">
<Columns>
<asp:BoundField DataField="Title" HeaderText="Title" />
<asp:BoundField DataField="Console" HeaderText="Console" />
<asp:BoundField DataField="Year_Released" HeaderText="Year Released" />
<asp:BoundField DataField="ESRB" HeaderText="ESRB Rating" />
<asp:BoundField DataField="Score" HeaderText="Personal Score" />
<asp:BoundField DataField="Publisher" HeaderText="Publisher" />
<asp:BoundField DataField="Developer" HeaderText="Developer" />
<asp:BoundField DataField="Genre" HeaderText="Genre" />
<asp:BoundField DataField="Purchase" HeaderText="Purchase Date" />
<asp:TemplateField ItemStyle-Width="7%" ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="lnkDetails" runat="server" Text="View" PostBackUrl='<%# "~/ViewDetails.aspx?RowIndex=" & Container.DataItemIndex %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the codebehind code on the page where I am trying to have the code be displayed is:
Example 1b
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Me.Page.PreviousPage IsNot Nothing Then
Dim rowIndex As Integer = Integer.Parse(Request.QueryString("RowIndex"))
Dim GridView1 As GridView = DirectCast(Me.Page.PreviousPage.FindControl("Grid1"), GridView)
Dim row As GridViewRow = GridView1.Rows(rowIndex)
lblTitle.Text = row.Cells(0).Text
lblConsole.Text = row.Cells(1).Text
lblYear.Text = row.Cells(2).Text
lblESRB.Text = row.Cells(3).Text
lblScore.Text = row.Cells(4).Text
lblPublisher.Text = row.Cells(5).Text
lblDeveloper.Text = row.Cells(6).Text
lblGenre.Text = row.Cells(7).Text
lblPurchase.Text = row.Cells(8).Text
End If
End Sub
I have also tried another set of code where the button on the gridview was:
Example 2a
<asp:Button ID="btnLink" runat="server" Text="View Details" PostBackUrl='<%# Eval("Title", "~/ViewDetails.aspx?Id={0}") %>'/>
Where the codebehind code is:
Example 2b
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Not IsPostBack Then
Dim GameTitle As String = Request.QueryString("Id")
Dim connString As String = "PROVIDER=Microsoft.ACE.OLEDB.12.0;" + "DATA SOURCE=" + Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "App_Data" + "db1.accdb")
Using connection As New OleDbConnection(connString)
connection.Open()
Dim reader As OleDbDataReader = Nothing
Dim command As New OleDbCommand((Convert.ToString("SELECT * from [Video_Games] WHERE Title='") & GameTitle) + "'", connection)
reader = command.ExecuteReader()
While reader.Read()
lblTitle.Text = reader(0).ToString()
lblConsole.Text = reader(1).ToString()
lblYear.Text = reader(2).ToString()
lblESRB.Text = reader(3).ToString()
lblScore.Text = reader(4).ToString()
lblPublisher.Text = reader(5).ToString()
lblDeveloper.Text = reader(6).ToString()
lblGenre.Text = reader(7).ToString()
lblPurchase.Text = Convert.ToDateTime(reader(8).ToString()).ToShortDateString()
End While
End Using
End If
End Sub
End Class
I have tried making variations of both, mainly the second, but whatever I try the labels are not populated with the row information. Any assistance would be appreciated, and I can post any other code needed, like how I populated the gridview. Thank you.
It was as simple as changing the AutoEventWireup to "true" in my .aspx file.
I have data I am trying to input into a gridview. I am looking up the number of rows for the gridview and adding data into them like this:
My "test" however does not get populated into the Submitted and Variance BoundFields in the Gridview. All that populates is the Company. Shouldn't "test" also populate in those other two columns?
Private Sub BindGrid()
Dim dt As New DataTable
dt.Columns.Add("Company")
dt.Columns.Add("Submitted")
dt.Columns.Add("Variance")
gvTally.DataSource = dt
Dim da As SqlClient.SqlDataAdapter
Dim strSQL2 As String
Dim Response As String = ""
strSQL2 = "SELECT [Company] FROM [Monetra].[dbo].[tbl_MonetraLogins]"
da = New SqlClient.SqlDataAdapter(strSQL2, System.Configuration.ConfigurationManager.AppSettings("MainConnectionString").ToString)
da.Fill(dt)
Dim dr As DataRow
For i As Integer = 0 To gvTally.Rows.Count - 1
dr = dt.NewRow
dr.Item("Company") = dt.Rows(i).Item("Company")
dr.Item("Submitted") = "test"
dr.Item("Variance") = "test"
dt.Rows.Add(dr)
Next
gvTally.DataSource = dt
gvTally.DataBind()
End Sub
Here is my ASP Grid:
<asp:GridView ID="gvTally" runat="server" EnableModelValidation="True"
AllowSorting="True" class="table table-condensed table-striped table-bordered table-hover no-margin" AutoGenerateColumns="False" Font-Size="Small">
<Columns>
<asp:BoundField DataField="Company" HeaderText="Company" >
<ItemStyle Width="180px" />
</asp:BoundField>
<asp:BoundField DataField="Submitted" HeaderText="Submitted" />
<asp:BoundField DataField="Variance" HeaderText="Variance" />
<asp:TemplateField HeaderText="Action" ShowHeader="False">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CssClass="btn btn-success btn-small hidden-phone" Text="View" CommandName="View" />
</ItemTemplate>
<ItemStyle Width="60px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
Try this vb code behind, then comment out my test
Private Sub BindGrid()
Dim dt_SQL_Results As New DataTable
'' Commenting out to use test data as I have no access to your database
'Dim da As SqlClient.SqlDataAdapter
'Dim strSQL2 As String
'Dim Response As String = ""
'strSQL2 = "SELECT [Company] FROM [Monetra].[dbo].[tbl_MonetraLogins]"
'da = New SqlClient.SqlDataAdapter(strSQL2, System.Configuration.ConfigurationManager.AppSettings("MainConnectionString").ToString)
'da.Fill(dt_SQL_Results)
'' Commenting out to use test data as I have no access to your database
'' Comment this block out after you test and uncomment the above code block
dt_SQL_Results.Columns.Add("Company")
Dim dr_SQL_Results As DataRow
For i As Integer = 0 To 5
dr_SQL_Results = dt_SQL_Results.NewRow
dr_SQL_Results.Item("Company") = "Company " & i
dt_SQL_Results.Rows.Add(dr_SQL_Results)
Next
'gvTally.DataSource = dt_SQL_Results
'gvTally.DataBind()
'' Comment this block out after you test and uncomment the above code block
Dim dt As New DataTable
dt.Columns.Add("Company")
dt.Columns.Add("Submitted")
dt.Columns.Add("Variance")
Dim dr As DataRow
For i As Integer = 0 To dt_SQL_Results.Rows.Count - 1
dr = dt.NewRow
dr.Item("Company") = dt_SQL_Results.Rows(i).Item("Company")
dr.Item("Submitted") = "test"
dr.Item("Variance") = "test"
dt.Rows.Add(dr)
Next
gvTally.DataSource = dt
gvTally.DataBind()
End Sub
I would like to dynamically update the results of a GridView based on characters that are entered into a textbox. My code currently works but only fires the update when the textbox loses focus or the user tabs out of the textbox. AutoPost is set to true for the textbox. I have the code to refresh the SQLDataSource, I just want the update to happen as the user enters characters in the textbox. I imagine this will require client side action, but not sure where to start. Thank you.
MARKUP
<asp:TextBox ID="txtSearch" runat="server" AutoPostBack="True" ViewStateMode="Enabled"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="NameFirst" HeaderText="First Name" SortExpression="NameFirst" />
<asp:BoundField DataField="NameLast" HeaderText="Last Name" SortExpression="NameLast" />
<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
<asp:BoundField DataField="State_ID" HeaderText="State" SortExpression="State_ID" />
</Columns>
</asp:GridView>
CODEBEHIND
Protected Sub txtSearch_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
GridData()
End Sub
Private Sub GridData()
Dim conString As String = ConfigurationManager.ConnectionStrings("MyConnectionString").ToString()
Dim sqlcon As New SqlConnection(conString)
Dim sqlcmd As SqlCommand
Dim da As SqlDataAdapter
Dim dt As New System.Data.DataTable()
Dim query As [String]
If txtsearch.Text = "" Then
query = "SELECT [Individual_ID], [NameFirst], [NameLast], [Address], [City], [State_ID], [ZipCode], [Comment] FROM [t_Individual] ORDER BY [NameLast], [NameFirst]"
Else
query = "SELECT [Individual_ID], [NameFirst], [NameLast], [Address], [City], [State_ID], [ZipCode], [Comment] FROM [t_Individual] WHERE [NameLast] LIKE N'%" + txtSearch.Text + "%' ORDER BY [NameLast], [NameFirst]"
End If
sqlcmd = New SqlCommand(query, sqlcon)
sqlcon.Open()
da = New SqlDataAdapter(sqlcmd)
dt.Clear()
da.Fill(dt)
If dt.Rows.Count > 0 Then
GridView1.DataSourceID = ""
GridView1.DataSource = dt
GridView1.DataBind()
Else
GridView1.DataBind()
End If
sqlcon.Close()
End Sub
Suppose I have two .aspx pages and a connection the the sql server database engine.
The first page, let's call it playground.aspx, I'm having a set of databound which using the stored procedure for SELECT function (using dataset for it).
Now in the second page, let's call it link.aspx, there are two textbox, suppose there are multiple data in the playground.aspx page and I want to retrieve Entity Code and Username data (from the playground.aspx's databound) and show it in the link.aspx's textbox.
How can I do that?
I was told to create some function, but I never dealt with a databound before, only with TextBox and Label, it really confused me.
Any help's appreciated, thank you.
EDIT (Here's the databound code)
<asp:Panel ID="PanelDGV" runat="server" Height="100%" ScrollBars="None" Width="100%">
<asp:GridView ID="DGV" runat="server" AutoGenerateColumns="False" GridLines="None"
AllowPaging="true" PageSize="2" CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt">
<Columns>
<asp:BoundField DataField="EntityCode" HeaderText="Entity Code" />
<asp:BoundField DataField="UserName" HeaderText="Username" />
<asp:BoundField DataField="DivCode" HeaderText="Div Code" />
<asp:BoundField DataField="GroupCode" HeaderText="Group Code" />
<asp:BoundField DataField="CreatedBy" HeaderText="Created By" />
<asp:BoundField DataField="CreatedOn" HeaderText="Created On" />
<asp:BoundField DataField="ModifiedBy" HeaderText="Modified By" />
<asp:BoundField DataField="ModifiedOn" HeaderText="Modified On" />
<asp:ButtonField ButtonType="Image" ImageUrl="../Support/Image/Edit.png" ItemStyle-HorizontalAlign="Center"
CommandName="CmdEdit" HeaderText="Edit">
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:ButtonField>
</Columns>
<PagerStyle CssClass="pgr"></PagerStyle>
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
</asp:GridView>
</asp:Panel>
I just solved the problem, here's the code
For link.vb
Public Function F01_sysUser_Select(ByVal EntityCode As String, ByVal Username As String) As ProcessResult
Try
Dim SqlCmd As New SqlCommand()
SqlCmd.Connection = New SqlConnection(CF.CfgConnectionString)
SqlCmd.CommandType = CommandType.StoredProcedure
SqlCmd.CommandTimeout = CF.CfgCommandTimeout
SqlCmd.CommandText = "sysUser_SelectByID"
SqlCmd.Parameters.Add("#EntityCode", SqlDbType.VarChar) : SqlCmd.Parameters(0).Value = EntityCode
SqlCmd.Connection.Open()
Dim Dr As SqlDataReader = SqlCmd.ExecuteReader(CommandBehavior.CloseConnection)
F01_Dt_sysUser.Clear()
F01_Dt_sysUser.Load(Dr)
If F01_Dt_sysUser.Rows.Count > 0 Then
Dr.Close()
Dr = Nothing
SqlCmd.Dispose()
Return ProcessResult.SuccessWithResult
Else
Dr.Close()
Dr = Nothing
SqlCmd.Dispose()
Return ProcessResult.SuccessWithNoResult
End If
Catch ex As Exception
InsertErrorLog("PlaygroundLink.F01_sysUser_Select", ex.Message)
ExMessage = ex.Message
Return ProcessResult.Failed
End Try
End Function
and in the link.aspx.vb:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim QSEntityCode As String
Dim QSUserName As String
QSEntityCode = Request.QueryString("QSEC").ToString
QSUserName = Request.QueryString("QSUN").ToString
Dim Bl As New PlaygroundLink
If Bl.F01_sysUser_Select(QSEntityCode, QSUserName) = CF.ProcessResult.SuccessWithResult Then
TbEntityCode.Text = QSEntityCode
TbUsername.Text = QSUserName
Else
' LblMessage.Text = Bl.ExMessage
End If
End Sub
lastly in playground.aspx.vb:
Private Sub DGV_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles DGV.RowCommand
If e.CommandName = "CmdEdit" Then
Dim QSEntityCode As String
Dim QSUserName As String
Dim idx As Integer = Convert.ToInt32(e.CommandArgument)
Dim row As GridViewRow = DGV.Rows(idx)
QSEntityCode = row.Cells(0).Text
QSUserName = row.Cells(1).Text
Response.Redirect(RR.PlaygroundLink & "?QSEC=" & QSEntityCode & "&QSUN=" & QSUserName)
End If
End Sub
After that, I get what I want, displaying the result in the link.aspx textbox, cheers! :)