Gridview with textboxes and SQL Server database - asp.net

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

Related

Object reference Error when filling textbox with data from database

I am trying to fill a text box with an ID of O1IDText when the selected value of a drop down list is changed. I get an error "Object reference not set to an instance of an object".
Here is my code in ASP of the drop down list:
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" AutoPostBack="true" runat="server" DataSourceID="SqlDataSource2" AppendDataBoundItems="true" OnDataBinding="DropDownlist1_DataBinding1" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" DataTextField="FullName" DataValueField="FullName" SelectedValue='<%# Bind("Official1") %>'>
</asp:DropDownList>
</EditItemTemplate>
Below is the code of my Textbox wihtin ASP:
<EditItemTemplate>
<asp:TextBox ID="O1IDText" runat="server" Text='<%# Bind("O1ID") %>'></asp:TextBox>
</EditItemTemplate>
And Finally my code behind in VB:
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim ddList As DropDownList = CType(sender, DropDownList)
RemoveHandler ddList.DataBinding, AddressOf DropDownlist1_DataBinding1
Dim O1IDText As TextBox = TryCast(FindControl("O1IDText"), TextBox)
Dim cmd As SqlCommand = con.CreateCommand()
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "Select ID from Official where [First Name] + ' ' + [Last Name]+ ' ' +[Email]+ ' ' +[Phone] = '" + ddList.SelectedValue + "'"
Dim dr As SqlDataReader
Try
con.Open()
dr = cmd.ExecuteReader()
dr.Read()
O1IDText.Text = dr("ID").ToString
Catch ex As Exception
con.Close()
End Try
The exception "Object reference not set to an instance of an object" happens during O1IDText.Text = dr("ID").ToString.
Assuming that the DropDownList and the TextBox are both in the same row or item, you can get the TextBox this way:
Dim O1DText As TextBox = CType(ddList.NamingContainer.FindControl("O1DText"), TextBox)

Gridview items not populating correctly

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

Dynamically update GridView results based on text entered into a textbox

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

Child gridview update event

I have problem regarding child gridview (gridview inside ListView), so far i solved the databind and the the Delete command , but i couldn't figure out the Edut Mode ( i click the image button) but the GV doesn't go to edit mode the codes are as follows: thanks in advance
Page mark-up:
EditItemTemplate
<asp:ImageButton ID="imgbUpdate" runat="server" CommandName="Update" Text="Update" ImageUrl="~/Images/save_icon_mono.gif" CausesValidation="true" ValidationGroup="vgrpSaveContact"/>
<asp:ImageButton ID="imgbCancel" runat="server" CommandName="Cancel" Text="Cancel" ImageUrl="~/Images/undo_icon_mono.gif" CausesValidation="false"/>
EditItemTemplate
<ItemTemplate>
<table>
<tr>
<td> <asp:ImageButton ID="imgbEdit" runat="server" CommandName="Edit" Text="Edit" ImageUrl="~/Images/edit_icon_mono.gif" />
</td>
<td> <asp:ImageButton ID="imgbDelete" runat="server" CommandName="Delete" Text="Delete" ImageUrl="~/Images/delete_icon_mono.gif" ToolTip="Delete"/>
</td>
</tr>
</table>
</ItemTemplate>
Code VB.NET
Protected Sub gvSorties_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
Dim connString As String = ConfigurationManager.ConnectionStrings("MoyensAeriensConnectionString").ConnectionString
Dim gvTemp As GridView = DirectCast(sender, GridView)
gvUniqueID = gvTemp.UniqueID
'Get the value
Dim strSortieID As String = DirectCast(gvTemp.Rows(e.RowIndex).FindControl("lblSortieID"), Label).Text
Using conn As New SqlConnection
conn.ConnectionString = connString
conn.Open()
Try
Dim strSQL As String = ""
Dim dsTemp As New SqlDataSource()
dsTemp.ConnectionString = connString
'Get the values stored in the text boxes
Dim strMissionNo As String = DirectCast(gvTemp.Rows(e.RowIndex).FindControl("txtMissionNo"), TextBox).Text
Dim strCaptain As String = DirectCast(gvTemp.Rows(e.RowIndex).FindControl("txtCaptain"), TextBox).Text
Dim strCrew As String = DirectCast(gvTemp.Rows(e.RowIndex).FindControl("txtCrew"), TextBox).Text
Dim strFuel As String = DirectCast(gvTemp.Rows(e.RowIndex).FindControl("txtFuel"), TextBox).Text
'Prepare the Update Command of the DataSource control
strSQL = "UPDATE Sortie set MissionNo = '" & strMissionNo & "'" & ",Captain = " & strCaptain & "" & ",Crew = '" & strCrew & "'" & ",Fuel = '" & strFuel & "'" & " WHERE SortieID = " & strSortieID
dsTemp.UpdateCommand = strSQL
dsTemp.Update()
'Reset Edit Index
gvEditIndex = -1
lvODV.DataBind()
conn.Close()
Catch
End Try
End Using
End Sub
Many thanks to every one

ASP.net GridView get database values

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

Resources