why button click insert data twice - asp.net

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.

Related

Edit Gridview update issue

I have got a gridview which when you press select on a row it transfers you to another gridview page,
which displays more columns from that table to give more detail about that row.
I know how to do this using:
<asp:HyperLinkField DataNavigateUrlFields="MISAppID" DataNavigateUrlFormatString="ApplicationsDetails.aspx?MISAppID={0}" Text="Select" />
In the 1st Gridview then using a Stored-procedure on the second page it displays the correct row using the ID field.
In my current site on the second page, I have added an edit button that does edit the row correctly in my database but on completion, it breaks the site and I can't work out how to get it to just refresh the gridview
This is the error I get:
Exception Details: System.NotSupportedException: Updating is not
supported by data source 'SqlDataSource1' unless UpdateCommand is
specified.
Is it the case that my BindGrid is missing something or is the way I am using my Stored-procedure?
Here is my VB code:
Public Sub BindGrid() Handles SqlDataSource1.Selecting
End Sub
Protected Sub OnRowEditing(sender As Object, e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
Me.BindGrid()
End Sub
Protected Sub OnRowUpdating(sender As Object, e As GridViewUpdateEventArgs)
Dim row As GridViewRow = GridView1.Rows(e.RowIndex)
Dim misappId As Integer = Convert.ToInt32(GridView1.DataKeys(e.RowIndex).Values(0))
Dim application As String = TryCast(row.Cells(2).Controls(0), TextBox).Text
Dim url As String = TryCast(row.Cells(3).Controls(0), TextBox).Text
Dim access_group As String = TryCast(row.Cells(4).Controls(0), TextBox).Text
Dim creator_ein As String = TryCast(row.Cells(5).Controls(0), TextBox).Text
Dim data_location As String = TryCast(row.Cells(6).Controls(0), TextBox).Text
Dim purpose As String = TryCast(row.Cells(7).Controls(0), TextBox).Text
Dim active As String = TryCast(row.Cells(8).Controls(0), TextBox).Text
Dim business_owner As String = TryCast(row.Cells(9).Controls(0), TextBox).Text
Dim area As String = TryCast(row.Cells(10).Controls(0), TextBox).Text
Dim constr As String = ConfigurationManager.ConnectionStrings("myLocalConnectionString").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("UPDATE tbl_AutomationCompassApplications SET Application = #Application, URL = #URL, Access_Group = #Access_Group, Creator_EIN = #Creator_EIN, Data_location = #Data_location, Purpose = #Purpose, Active = #Active, Business_Owner = #Business_Owner, Area = #Area WHERE MISAppID = #MISAppID")
cmd.Parameters.AddWithValue("#MISAppID", misappId)
cmd.Parameters.AddWithValue("#Application", application)
cmd.Parameters.AddWithValue("#URL", url)
cmd.Parameters.AddWithValue("#Access_Group", access_group)
cmd.Parameters.AddWithValue("#Creator_EIN", creator_ein)
cmd.Parameters.AddWithValue("#Data_location", data_location)
cmd.Parameters.AddWithValue("#Purpose", purpose)
cmd.Parameters.AddWithValue("#Active", active)
cmd.Parameters.AddWithValue("#Business_Owner", business_owner)
cmd.Parameters.AddWithValue("#Area", area)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
GridView1.EditIndex = -1
Me.BindGrid()
End Sub
Ok, say we have a list of hotels - we want to display them, and then click on a row to eit.
(and you writing WAY too much code here).
So, lets say we drop in a gridview. Use the connection wizard - let it generate the markup.
THEN REMOVE the data source on the page, remove the datasource property of the gridview.
So, in less time then it takes me to write above? We have this markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="cmdView" runat="server" Text="Edit"
PK = '<%# Container.DataItemIndex %>' OnClick="cmdView_Click" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="City" HeaderText="City" />
</Columns>
</asp:GridView>
Note the cool trick I used to get the PK row index.
When you are looking at the grid, you can't double click on the button to wire up a event (code behind), but you CAN DO THIS!!!!
Note VERY care full in above - I typed in OnClick "=", when you HIT "=", then NOTE the inteli-sense that popped up - the create NEW event is what we need. Click on create new event - NOTHING seems to happen, but if we NOW go to code behind, we have a code stub for the button!!!
And note how I needed/wanted the PK row value - so I just shoved in and created my OWN custom attribute for that button. ("PK").
Ok, so our code to load up the grid is now this - and I included the button click code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = False Then
LoadGrid()
End If
End Sub
Sub LoadGrid()
Dim strSQL As String
strSQL = "SELECT * from tblHotels Order by HotelName"
Using cmdSQL As New SqlCommand(strSQL, New SqlConnection(My.Settings.TEST3))
cmdSQL.Connection.Open()
Dim MyTable As New DataTable
MyTable.Load(cmdSQL.ExecuteReader)
GridView1.DataSource = MyTable
GridView1.DataBind()
Session("MyTable") = MyTable
End Using
End Sub
Protected Sub cmdView_Click(sender As Object, e As EventArgs)
Dim MyBtn As Button = sender
Session("RowID") = MyBtn.Attributes.Item("PK")
Response.Redirect("~/EditHotel.aspx")
End Sub
Look how clean and simple the above is!!! I find this as easy say as MS-Access coding!!!
Ok, so the grid now looks like this:
Note the button click code.
So, our markup is this for the new page (to edit hte ONE row).
<div style="float:left;width:20%">
<div style="text-align:right">
First Name :<asp:TextBox ID="txtFirstname" runat="server" Width="150"></asp:TextBox> <br />
Last Name :<asp:TextBox ID="txtLastname" runat="server" Width="150"></asp:TextBox> <br />
Hotel Name :<asp:TextBox ID="txtHotel" runat="server" Width="150"></asp:TextBox> <br />
City :<asp:TextBox ID="txtCity" runat="server" Width="150"></asp:TextBox> <br />
Active :<asp:CheckBox ID="Active" runat="server" Width="150"></asp:CheckBox>
</div>
</div>
<div style="clear:both">
<br />
<asp:Button ID="cmdSave" runat="server" Text ="Save " />
<asp:Button ID="cmdCancel" runat="server" Text="Cancel" Style="margin-left:20px" />
</div>
</form>
and it looks like this:
and the load code and save button code for this page?
This:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = False Then
LoadInfo()
End If
End Sub
Sub LoadInfo()
Dim MyTable As DataTable = Session("MyTable")
Dim MyRow As DataRow = MyTable.Rows(Session("RowID"))
txtFirstname.Text = MyRow("FirstName")
txtLastname.Text = MyRow("LastName")
txtCity.Text = MyRow("City")
txtHotel.Text = MyRow("HotelName")
Active.Checked = MyRow("Active")
End Sub
Protected Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click
Dim MyTable As DataTable = Session("MyTable")
Dim MyRow As DataRow = MyTable.Rows(Session("RowID"))
MyRow("FirstName") = txtFirstname.Text
MyRow("LastName") = txtLastname.Text
MyRow("City") = txtCity.Text
MyRow("HotelName") = txtHotel.Text
MyRow("Active") = Active.Checked
Using cmdSQL As New SqlCommand("SELECT * from tblHotels where ID = 0",
New SqlConnection(My.Settings.TEST3))
Dim da As New SqlDataAdapter(cmdSQL)
Dim cmdUpdate As New SqlCommandBuilder(da)
da.Update(MyTable)
End Using
Response.Redirect("~/MyTours.aspx")
End Sub
Again, look how easy, clean and readable the code is.
Study the above example - you see that you don't need all that parameters code, and you see how little code is in fact required to select a row - jump to page to edit, and then you hit save - update the data and jump back to the grid row page.

copy row from asp.net gridview to new page using VB

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.

How do I use the selected property to selected parameters of an Insert query with drop down list

I am using a grid, drop down box and button to insert information of an order into an order table on sqlserver (in visual studio - all tables have records except the order table) - I am not sure how to incorporate all three in order to update the table though. When the logged in user clicks on their selected item - chooses a pharmacy and clicks the confirm button this should update.
Grid:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" Text="Select" CommandName="UpdateMedicine" CommandArgument='<%# Eval("MedicineId") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Purpose" HeaderText="Purpose" />
<asp:BoundField DataField="Instrcutions" HeaderText="Instructions" />
</Columns>
</asp:GridView>
Code for grid:
Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
If e.CommandName = "UpdateMedicine" Then
Dim MedicineID As Integer = Integer.Parse(e.CommandArgument.ToString())
End If
End Sub
Dropdown - button .click
<asp:DropDownList ID="DropPharm" runat="server" DataSourceID="SqlPharm" DataTextField="Pharmname" DataValueField="Pharmname"></asp:DropDownList>
<br />
<br />
<asp:Button ID="btnconfirm" runat="server" Text="Confirm" />
Code for button:
Protected Sub btnconfirm_Click(sender As Object, e As EventArgs) Handles btnconfirm.Click
Dim strPatientId As Integer = Session("PatientId").ToString
Dim strMedicineId As Integer
Dim strDoctorId As Integer
Dim strPharmacyId As Integer
Dim strDateOrdered As Date
Dim query As String = String.Empty
query &= "INSERT INTO Order_pres (PatientId, MedicineId, PharmacyId, "
query &= " DoctorId, [Date Ordered]) "
query &= "VALUES (#PatientId,#MedicineId, #PharmacyId, #DoctorId, #DateOrdered)"
Using conn As New SqlConnection("SurgeryConnectionString"), _
comm As New SqlCommand(query, conn)
With comm.Parameters
.Add("#PatientId", SqlDbType.Int).Value = CInt(strPatientId)
.Add("#MedicineId", SqlDbType.Int).Value = CInt(strMedicineId)
.Add("#PharmacyId", SqlDbType.Int).Value = CInt(strPharmacyId)
.Add("#DoctorId", SqlDbType.Int).Value = CInt(strDoctorId)
.Add("#DateOrdered", SqlDbType.DateTime).Value = DateTime.Parse(strDateOrdered)
End With
Try
conn.Open()
comm.ExecuteNonQuery()
lblconfirm.Text() = "Order Placed"
Catch ex As SqlException
lblnoconfirm.Text() = "Order not placed"
End Try
End Using
End Sub
I have been stuck on this for quite some time if any one could give me some direction or an example I would appreciate it very much:) - thank you
I hope this is what you're wanting.
To get the value or text from the dropdownlist use:
someVariable = DropPharm.SelectedItem.Text
someVariable = DropPharm.SelectedItem.Value
To get the selected row's cell values use:
someVariable = GridView1.Rows(GridView1.SelectedIndex).Cells(yourColumnIndex).Value
Use this to set your variables in the btnconfirm_Click sub.
Make MedicineID a class level variable so declare it outside all the subs but inside of your class so you can access it's value in another sub. Then in your btn click sub:
Dim strMedicineId As Integer = MedicineID
Then do an IF EXISTS in your query so you can update it if it already exists in the database with something like:
IF EXISTS (SELECT * FROM Order_pres WHERE MedicineID=#MedicineID AND PatientID=#PatientID AND PharmacyID=#PharmacyID AND.....)
UPDATE Order_press SET (…) WHERE MedicineID=#MedicineID AND....
ELSE
INSERT INTO Order_pres (…) VALUES (..)

Gridview: editing after searching

MY search button is linked to a GridvieW, which has an edit button on every row. When I press search button, data changes and a databind() occurs.
After that, If I try to use the edit button it displays another row to edit, not the selected one(biggest problem).Both buttons work well when tested separately, but not one after another. I solved that removing GridView1.DataBind() from edit button event, but then It will require 2 clicks to display the edit template(another problem).
EDIT: I guess teh problem is in the search button. Can you give a good search code that doesn't depend of sqldatasource?
'Where data is loaded into GV
Dim SqlDataSource1 As New SqlDataSource
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
SqlDataSource1.SelectCommand = "SELECT * FROM [TABLE]"
SqlDataSource1.ConnectionString = "Conn String"
If Not IsPostBack Then
Dim conn As New SqlConnection
conn.ConnectionString = con.GetConnectionString
Dim cmd As New SqlCommand()
cmd.CommandText = "SELECT [AREA], [LEADER_USER] FROM [AREA]"
cmd.CommandType = CommandType.Text
cmd.Connection = conn
conn.Open()
Dim adpt As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
adpt.Fill(ds)
GridView1.DataSource = ds
GridView1.DataBind()
conn.Close()
End If
End Sub
'Search button
Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Try
SqlDataSource1.SelectCommand = "SELECT * FROM TABLE WHERE id LIKE #id"
SqlDataSource1.SelectParameters.Clear()
SqlDataSource1.SelectParameters.Add(New Parameter("id", DbType.String, "%" + txtSearch.Text + "%"))
GridView1.DataSource = SqlDataSource1
GridView1.DataBind()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
'Edit button
Protected Sub EditRow(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
GridView1.DataSource = SqlDataSource1
GridView1.DataBind()
End Sub
Markup:
<asp:TextBox ID="TextBox1" runat="server" BackColor="#D9ECFF"
style="height: 20px; width: 186px" AutoPostBack="True"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" BackColor="#0066cc"
BorderColor="#0066cc" BorderStyle="Outset" Font-Bold="True" ForeColor="White"
style=" height: 26px; width: 56px" Text="Search" />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" CellPadding="4" OnRowEditing="EditRow"
OnRowCancelingEdit="CancelEditRow" DataKeyNames="AREA" DataMember="DefaultView">
<Columns>
<asp:BoundField DataField="AREA" HeaderText="AREA" ReadOnly="True"
SortExpression="AREA" />
<asp:TemplateField HeaderText="LEADER_USER" SortExpression="LEADER_USER">
<ItemTemplate><%#Eval("leader_user")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtleaderuser" runat="server" Text='<%#Eval("leader_user")%>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="editButton" runat="server" CommandName="Edit"
ImageUrl="images/pencil1.png" Text="Edit" ToolTip="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="BtnUpdate" runat="server" CommandName="Update"
Text="Update" />
<asp:Button ID="BtnCancel" runat="server" CommandName="Cancel"
Text="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Please help me. How are these 2 gridview functionalities supposed to be coded to work together? This is the only way I know how to do this, but any idea is ok for me if it works. If you are a C# guy, you ca use a C#-to VB converter:
http://www.developerfusion.com/tools/convert/csharp-to-vb/
Try this :
fill_grid()
{
// populate your grid
SqlCommand cmd = new SqlCommand();
cmd.CommandText = " your select statement ";
cmd.CommandType = CommandType.Text;
cmd.Connection = this.sqlConnection1;
this.yourConnection .Open();
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adpt.Fill(ds);
yourGrid.DataSource = ds;
yourGrid.DataBind();
this.sqlConnection1.Close();
}
Then hook to the button click event of your search button like this :
yourButton_Click ((object sender, EventArgs e)
{
GridViewRow clickedRow = ((Button)sender).NamingContainer as GridViewRow;
//Then find your parameter from your textbox in the clicked row
TextBox yourbox = (TextBox)clickedRow.FindControl("your_box");
//Here is where you would all your search logic whatever that is
}
Then you could still use your row_updating event independently of the search button click event.
you can add Where statement in page_load by if command and delete where in btnSearch_Click function. like this
if (txtSearch.Text.length()>0)
SqlDataSource1.SelectCommand += "WHERE id LIKE #id"
then it works properly

Checkbox update in GridView

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

Resources