Search in Repeater - asp.net

On pageload I want to show all fields in the repeater control and on typing licenseid in the textbox I want to show that specific licenceid details.
If I place below code in the datasource of repeater the first one is not working. In the second one I placed a textbox and set its value to 0 on pageload. It is working. But I want both to be working.
SELECT * FROM License WHERE (0 = #selectAll OR LicenseID=#LicenseID) -> Not working
SELECT * FROM License WHERE (0 = #selectAll ) ->working
SELECT * FROM License WHERE (LicenseID=#LicenseID)-> working
Binding Code
Protected Sub BindRepeater()
Dim cmd As New SqlCommand("Select * from License", con)
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim ds As New DataSet()
Dim adp As New SqlDataAdapter(cmd)
adp.Fill(ds)
Repeater1.DataBind()
con.Close()
End Sub

Protected Sub BindRepeater(int licenseID)
string qry = "Select * from License WHERE 1=1";
if(licenseID>0) qry += " AND LicenseID=" + licenseID.ToString();
Dim cmd As New SqlCommand(qry, con)
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim ds As New DataSet()
Dim adp As New SqlDataAdapter(cmd)
adp.Fill(ds)
Repeater1.DataBind()
con.Close()
End Sub

Related

Search function fail

I would like to search data in a textbox . Below is my code. I tried to search but nothing happen.
If Not Me.IsPostBack Then
Me.SearchPanelId()
End If
End Sub
Private Sub SearchPanelId()
Dim ConnectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Using con As New SqlConnection(ConnectionString)
Using cmd As New SqlCommand()
Dim sql As String = "SELECT panelid, panelname, paneltype FROM PANEL_TABLE"
If Not String.IsNullOrEmpty(TextBox1.Text.Trim()) Then
sql += " WHERE panelid LIKE #panelid + '%'"
cmd.Parameters.AddWithValue("#panelid", TextBox1.Text.Trim())
End If
cmd.CommandText = sql
cmd.Connection = con
Using sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
End Sub
Protected Sub Search(sender As Object, e As EventArgs)
Me.SearchPanelId()
End Sub
Protected Sub OnPaging(sender As Object, e As GridViewPageEventArgs)
GridView1.PageIndex = e.NewPageIndex
Me.SearchPanelId()
End Sub
Do the validation before you start creating objects. You need to check if that datatype of the ID is valid. I guessed that this was an Integer type but check your database. If I am wrong and the datatype is .VarChar then see the second rendition. :-) The Like keyword does not make any sense with a numeric field.
Don't use .AddWithValue See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
A DataAdapter is not necessary. Just use the load method of the DataTable.
Private Sub SearchPanelId()
Dim IDValue As Integer
Dim dt As New DataTable
If String.IsNullOrEmpty(TextBox1.Text.Trim()) OrElse Not Integer.TryParse(TextBox1.Text.Trim, IDValue) Then
Return
End If
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Using cmd As New SqlCommand("SELECT panelid, panelname, paneltype FROM PANEL_TABLE WHERE panelid = #panelid", con)
cmd.Parameters.Add("#panelid", SqlDbType.Int).Value = IDValue
con.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
If Id is a .VarChar
Private Sub SearchPanelId()
Dim dt As New DataTable
If String.IsNullOrEmpty(TextBox1.Text.Trim()) Then
Return
End If
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Using cmd As New SqlCommand("SELECT panelid, panelname, paneltype FROM PANEL_TABLE WHERE panelid Like #panelid", con)
cmd.Parameters.Add("#panelid", SqlDbType.VarChar).Value = TextBox1.Text.Trim() & "%"
con.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
GridView1.DataSource = dt
GridView1.DataBind()
End Sub

Asp.net multible table access vb.net

and good day..
I have a code of asp.net in vb.net and work fine for one table but i need to add multible table of( master and dr ) to code the data is the sum from the two table but its different. can anyone help me..thanks advance for all
Private Sub getData(ByVal user As String)
Dim dt As New DataTable()
Dim connectionString As String
Dim connection As OleDbConnection
connectionString = ConfigurationManager.ConnectionStrings("Data_For_netConnectionString").ToString
connection = New OleDbConnection(connectionString)
connection.Open()
Dim sqlCmd As New OleDbCommand("SELECT * from master WHERE UserID = #user", connection)
sqlCmd.CommandText = _
"SELECT name, manistry, university, send, card FROM master "
Dim sqlDa As New OleDbDataAdapter(sqlCmd)
sqlCmd.Parameters.AddWithValue("#user", user)
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
TextBox1.Text = dt.Rows(0)("manistry").ToString
TextBox2.Text = dt.Rows(0)("university").ToString
TextBox4.Text = dt.Rows(0)("send").ToString
TextBox21.Text = dt.Rows(0)("card").ToString
name.Text = dt.Rows(0)("name").ToString
End If
connection.Close()
End Sub

asp.net DropDownList postback not executing method on first postback

I'm facing very un natural problem suddenly. I have DropDownList with autopostback is true. Postback executes a method which populates other things onpage according to selection. Now When I select any value first time from that dropdown then page gets postback but nothing get populate but from second time it works fine. Even I put breakpoint on that dropdown & it's not even hitting breakpoint for first postback.
<asp:DropDownList ID="ClientCode" runat="server" ClientIDMode="Static" CssClass="field-pitch" AutoPostBack="true"></asp:DropDownList>
Private Sub ClientCode_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ClientCode.SelectedIndexChanged
Me.populateConsignerDetails()
End Sub
Private Sub populateConsignerDetails()
Try
Dim str As String = "SELECT * FROM clientsDetails WHERE clientID = #clientID"
con.Open()
Dim cmd As New MySqlCommand(str, con)
cmd.Parameters.AddWithValue("#clientID", ClientCode.SelectedItem.ToString)
Dim da As New MySqlDataAdapter(cmd)
Dim dt As New DataTable
da.Fill(dt)
con.Close()
Dim payingParty As String = String.Empty
If dt.Rows.Count > 0 Then
consignerName.Text = dt.Rows(0)("clientName").ToString
consignerAddress.Text = dt.Rows(0)("companyAddress").ToString
consignerMobile1.Text = dt.Rows(0)("contactNumber1").ToString
consignerCity.Text = dt.Rows(0)("city").ToString
consignerState.Text = dt.Rows(0)("state").ToString
consignerPinCode.Text = dt.Rows(0)("pinCode").ToString
End If
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Update
Private Sub myadmin_shipment_details2_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
populateClient()
End If
End Sub
Private Sub populateClient()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "Select * from clientsDetails where status = 'active'"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("clientID").ToString()
item.Value = sdr("ClientName").ToString()
ClientCode.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End Sub

How to delete data in database using grid view in vb.net

I'm a beginner in vb.net. Currently I'm develop a simple application by using a grid view. however, I'm facing a problem in deleting the data. When I click delete button, it keep adding the blank line. and this blank line is affected my database also. and this blank line also can't be deleted from database manually.
here my code behind
`Imports System.Data.SqlClient
Imports System.Drawing
Imports System.Data
Imports System.Configuration
Imports System.Linq
Partial Class test2
Inherits System.Web.UI.Page
Dim AMS As String = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("AMS").ConnectionString
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Me.BindData()
End If
End Sub
Private Sub BindData()
Dim dt As DataTable = New DataTable
Dim strConnString As String = ConfigurationManager.ConnectionStrings("AMS").ConnectionString
Using con As SqlConnection = New SqlConnection(strConnString)
Dim strQuery As String = "SELECT * FROM ModuleDetail"
Using cmd As SqlCommand = New SqlCommand(strQuery)
Dim sda As SqlDataAdapter = New SqlDataAdapter
cmd.Connection = con
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Sub
Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
Dim IsDeleted As Boolean = False
Dim ModuleID As String = Convert.ToInt32(GridView1.DataKeys(e.RowIndex).Value.ToString())
Dim ModuleName As Label = CType(GridView1.Rows(e.RowIndex).FindControl("lblModuleName"), Label)
Dim SubModule As Label = CType(GridView1.Rows(e.RowIndex).FindControl("lblSubModule"), Label)
Dim strConnString As String = ConfigurationManager.ConnectionStrings("AMS").ConnectionString
Using con As SqlConnection = New SqlConnection(strConnString)
Using cmd As SqlCommand = New SqlCommand
cmd.CommandType = CommandType.Text
cmd.CommandText = "DELETE FROM ModuleDetail WHERE ModuleID=#ModuleID"
cmd.Parameters.AddWithValue("#ModuleID", ModuleID)
cmd.Connection = con
con.Open()
IsDeleted = cmd.ExecuteNonQuery() > 0
con.Close()
GridView1.DataSource = cmd
GridView1.DataBind()
End Using
End Using
If IsDeleted Then
lblMsg.Text = "'" & SubModule.Text & "' details has been deleted successfully!"
lblMsg.ForeColor = System.Drawing.Color.Green
BindData()
Else
lblMsg.Text = "Error while deleting '" & SubModule.Text & "' details"
lblMsg.ForeColor = System.Drawing.Color.Red
End If
End Sub
`
I have try a few code from others sources but it shows the same logic error which keep adding the blank line. I hope you guys can help me to solve the issue.
Though it might not relevant to your problem context, but I have observed a couple of issues from your code:
1) It seems you are binding grid twice after row delete.
2) Try commenting following lines since you already calling BindData() whithin IsDeleted flag check.
GridView1.DataSource = cmd;
GridView1.DataBind();
3) You are assigning the 'Command' object: cmd to the Grid's datasource which is not correct. Check your BindData(...) method how you need to bind Grid actually.

NullReferenceException - Object reference not set to an instance of an object

I am trying to run this code below. It was working previously, but when I added a second datareader, it stopped. Can anyone tell me what's wrong ?
Protected Sub btnSearchUser_Click(sender As Object, e As EventArgs) Handles btnSearchUser.Click
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim searchComm As String = "SELECT * FROM users WHERE username LIKE #username"
Dim user_id_select As New Integer
Dim searchSQL As New SqlCommand
conn.Open()
searchSQL = New SqlCommand(searchComm, conn)
searchSQL.Parameters.AddWithValue("#username", txtUserSearch.Text)
Dim datareader As SqlDataReader = searchSQL.ExecuteReader()
While datareader.Read
lstUsers.Items.Add(datareader.Item("username"))
End While
datareader.Close()
conn.Close()
Dim conn2 As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim selectComm As String = "SELECT user_id FROM users WHERE username=#username_selected"
Dim selectSQL As New SqlCommand
conn2.Open()
selectSQL = New SqlCommand(selectComm, conn2)
selectSQL.Parameters.AddWithValue("#username_selected", lstUsers.SelectedItem.Text.Trim)
Dim datareader2 As SqlDataReader = selectSQL.ExecuteReader()
While datareader2.Read
If datareader2.HasRows Then
user_id_select = datareader2("user_id")
lblUserSelected.Text = "Selected: " + lstUsers.SelectedItem.Text
ElseIf datareader2.HasRows = False Then
lblInvalidUsername.Visible = True
datareader2.Close()
End If
End While
conn2.Close()
End Sub
Hi,
I'm gettin a NullReference exception on lblUserSelected.Text = "Selected: " + lstUsers.SelectedItem.Text whenever I enter a username in txtUserSearch and click search, it was working previously.. I don't know what happened..
Can anyone tell me whats wrong?
I assume you're getting the NullReferenceException on this line:
selectSQL.Parameters.AddWithValue("#username_selected", lstUsers.SelectedItem.Text.Trim)
since you haven't specified the SelectedItem of the recently filled ListBox. To select the first item you could use this code:
While datareader.Read
lstUsers.Items.Add(datareader.Item("username"))
End While
If lstUsers.Items.Count <> 0 Then lstUsers.SelectedIndex = 0
You are also not handling the case that there are no usernames in the database, then the ListBox is empty and has no selected-item.

Resources