Checkbox update in GridView - asp.net

When people search on my website using a GridView I would like to have a checkbox column that they click on which will change the value in a column called STATUS to U. I'm having a heck of a time finding code that works so I was hoping you guys could help. I'm a COMPLETE NOOB so please be descriptive if you know the answer.
Code for Checkbox button - Currently when I search it comes back saying that it cannot convert string to boolean.
<asp:TemplateField HeaderText="Successful Contact?">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" checked='<%#Bind("status")%>' AutoPostBack="true" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" checked='<%#Bind("status")%>'
Enabled="False" /></ItemTemplate>
</asp:TemplateField>
This is the vb code
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
For Each GridViewRow In GridView1.Rows
Dim row As GridViewRow = GridView1.Rows(e.RowIndex)
Dim value As Boolean
value = DirectCast(GridView1.Rows(e.RowIndex).Cells(0).FindControl("CheckBox1"), CheckBox).Checked
Dim connectionString As String = ConfigurationManager.ConnectionStrings("Data Source=server;Initial Catalog=i3FCC01;Integrated Security=True;").ConnectionString
Dim com_sql As New SqlClient.SqlCommand
Dim insertSql As String
insertSql = "Update CallQueueFCC Set Status='U' where Id = #id"
Using myConnection As New SqlConnection(connectionString)
myConnection.Open()
Dim myCommand As New SqlCommand(insertSql, myConnection)
myCommand.Parameters.AddWithValue("#status", value)
myCommand.ExecuteNonQuery()
myConnection.Close()
End Using
Next
GridView1.EditIndex = -1
DataBind()
End Sub

You are binding Status value for check box checked attribute which takes Boolean value.
But status has string value as you are binding string to Boolean it is throwing error.

Like Kiran mentioned earlier, status has a string value so you need to do some firefighting in the row databound event.
Markup
<asp:TemplateField HeaderText="Successful Contact?">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server"
Enabled="False" /></ItemTemplate>
</asp:TemplateField>
Code behind
Protected Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
'Evaluate the state of the check box, true when status =U , and false otherwise
Dim itemstatus As Boolean=If(DataBinder.Eval(e.Row.DataItem, "Status"), True, False)
Dim CheckBoxItemTemp As CheckBox=CType(e.Row.FindControl("CheckBox1"), CheckBox)
CheckBoxItemTemp.Checked=itemstatus
End if
If e.Row.RowState & DataControlRowState.Edit Then
'same as above but now for edit item template
Dim editstatus As Boolean=If(DataBinder.Eval(e.Row.DataItem, "Status"), True, False)
Dim CheckBoxEditTemp As CheckBox=CType(e.Row.FindControl("CheckBox1"), CheckBox)
CheckBoxEditTemp.Checked=editstatus
End if
End Sub

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 button click insert data twice

i have this button which i add in row of data however, i only add two row of the date, when click this button it give me 4 data, each date is being inserted twice meaning date A den date B den date A and den date B, what the problem
Protected Sub Button2_Click(sender As Object, e As System.EventArgs) Handles Button2.Click
Dim rowIndex As Integer = 0
Dim sc As New StringCollection()
Dim sc1 As New Date
If ViewState("CurrentTable") IsNot Nothing Then
Dim dtCurrentTable As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
Dim drCurrentRow As DataRow = Nothing
If dtCurrentTable.Rows.Count < 10 Then
For i As Integer = 1 To dtCurrentTable.Rows.Count
'extract the TextBox values
Dim box5 As TextBox = DirectCast(Gridview3.Rows(rowIndex).Cells(1).FindControl("TextBox5"), TextBox)
Dim box7 As Date = Convert.ToDateTime(box5.Text)
Dim myConn As New SqlConnection
Dim myCmd As New SqlCommand
myConn.ConnectionString = ConfigurationManager.ConnectionStrings("mydatabase").ConnectionString
Dim cmd As String
cmd = "Insert into Date values (#date) "
myCmd.CommandText = cmd
myCmd.CommandType = CommandType.Text
myCmd.Parameters.Add(New SqlParameter("#date", box7))
myCmd.Connection = myConn
myConn.Open()
myCmd.ExecuteNonQuery()
myCmd.Dispose()
myConn.Dispose()
rowIndex += 1
Next
End If
Else
' lblMessage.Text = "Cannot save as there no information recorded"
MsgBox("failed")
End If
End Sub
<asp:GridView ID="Gridview3" runat="server" AutoGenerateColumns="False"
Height="89px" ShowFooter="True" Width="303px">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="No of Available:" />
<asp:TemplateField HeaderText="New Date Available :">
<ItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" />
<AjaxToolkit:CalendarExtender ID="calExtender6" runat="server"
Format="dd/MM/yyyy" OnClientDateSelectionChanged="CheckDateEalier"
TargetControlID="TextBox5" />
</ItemTemplate>
<FooterStyle Height="22px" HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" onclick="ButtonAdd_Click"
Text="Add New Row" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView> 
Protected Sub ButtonAdd_Click(sender As Object, e As System.EventArgs)
AddNewRowToGrid()
End Sub
You called the function twice, once when you declare "Handles Button2.Click" and second when you set the onclick="ButtonAdd_Click".
You need to choose one of the options.
Hope that's help
Please check in the view page. I have experienced a similar issue like this in my struts,spring,hibernate application. My action method was called twice. This is because i have give the tag for the button as submit. something like <button:submit... . Just ensure that your method is called once or twice.
I had a similar problem, I created another button and copied all codes of the first button and inserted behind the new button, now the problem has solved.
it worked for me.

Repeater Button CommandArgument is Empty String

Losing my mind with this one. My button gets a commandargument of empty string even though the commandargument gets set. I have verified it gets set to the correct ID in debug mode, but then when I go to access this commandargument later in the repeaters ItemCommand event the commandarguments are empty string. And I have no idea why. I end up getting a sq foreign key exception because it is inserting an ID of 0 from the empty string values. There is no other code regarding the repeaters buttons that would be resetting it.
Repeater:
<asp:Repeater ID="repeaterAddresses" ViewStateMode="Enabled" DataSourceID="sqlFacilityAddresses" runat="server">
<ItemTemplate>
<Select:Address ID="AddressControl" runat="server" />
<asp:Button ID="btnMarkAsBilling" runat="server" EnableViewState="true" CommandName="Billing" Text="Mark as billing address" />
<asp:button ID="btnMarkAsPhysical" runat="server" EnableViewState="true" CommandName="Physical" Text="Mark as physical address" />
</ItemTemplate>
</asp:Repeater>
Code behind:
Protected Sub repeaterAddresses_ItemCreated(ByVal sender As Object, ByVal e As RepeaterItemEventArgs) Handles repeaterAddresses.ItemCreated
If Not IsNothing(DirectCast(e.Item.DataItem, DataRowView)) Then
If (e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim addressControl As Address = DirectCast(e.Item.FindControl("AddressControl"), Address)
addressControl.AddressID = CInt(DirectCast(e.Item.DataItem, DataRowView)("Address_ID").ToString())
Dim btnBilling As Button = DirectCast(e.Item.FindControl("btnMarkAsBilling"), Button)
btnBilling.CommandArgument = CInt(DirectCast(e.Item.DataItem, DataRowView)("Address_ID").ToString())
Dim btnPhysical As Button = DirectCast(e.Item.FindControl("btnMarkAsPhysical"), Button)
btnPhysical.CommandArgument = CInt(DirectCast(e.Item.DataItem, DataRowView)("Address_ID").ToString())
End If
End If
End Sub
Protected Sub repeaterAddress_ItemCommand(ByVal sender As Object, ByVal e As RepeaterCommandEventArgs) Handles repeaterAddresses.ItemCommand
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("Trustaff_ESig2").ConnectionString)
Dim button As Button = CType(e.CommandSource, Button)
Select Case e.CommandName
Case "Billing"
Dim cmdBillingAddress As New SqlCommand("[SP_Facility_UpdateBillingAddress]", conn)
With cmdBillingAddress
.CommandType = CommandType.StoredProcedure
.Parameters.Add(New SqlParameter("#Facility_ID", DbType.Int32)).Value = sqlFacilityAddresses.SelectParameters("Facility_ID").DefaultValue
.Parameters.Add(New SqlParameter("#BillingAddress_ID", DbType.Int32)).Value = e.CommandArgument
End With
conn.Open()
cmdBillingAddress.ExecuteNonQuery()
conn.Close()
Case "Physical"
Dim cmdPhysicalAddress As New SqlCommand("[SP_Facility_UpdatePhysicalAddress]", conn)
With cmdPhysicalAddress
.CommandType = CommandType.StoredProcedure
.Parameters.Add(New SqlParameter("#Facility_ID", DbType.Int32)).Value = sqlFacilityAddresses.SelectParameters("Facility_ID").DefaultValue
.Parameters.Add(New SqlParameter("#PhysicalAddress_ID", DbType.Int32)).Value = e.CommandArgument
End With
conn.Open()
cmdPhysicalAddress.ExecuteNonQuery()
conn.Close()
End Select
PopulateBillingPhysicalAddresses(sqlFacilityAddresses.SelectParameters("Facility_ID").DefaultValue)
End Sub
Try this:
<asp:Button ID="btnMarkAsBilling" runat="server" EnableViewState="true"
CommandName="Billing" Text="Mark as billing address"
CommandArgument='<%# Eval("Address_ID") %>'/>
Note the single quotes around the attribute value. ASP.NET will not execute the server side data binding code if they are double quotes. You'll need to remove the CommandArgument assignments from your code behind.
Address_ID will need to be a property on the object you are databinding to the repeater.

Resources