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.
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.
Is possible to transfer data from one table into an empty table along with a other data? Is it possible to do that with a single SQL statement? What I've tried so far produces no errors but the data from the original table is not transferred to the empty table.
I've include my code below and I'd appreciate any advice. I suspect there's a problem with the database connection, but I am still new to programming and I can't see the problem.
Imports System.Data.SqlClient
Public Class uploadSuccess
Inherits System.Web.UI.Page
Dim con As SqlConnection
Dim cmd As SqlCommand
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
con = New SqlConnection("Data Source=127.0.0.1; User Id=user;Password=pass;Initial Catalog=catalog;")
con.Open()
cmd = con.CreateCommand()
cmd.Connection = con
Dim intCount As Int32
Dim getReceipt As Int32
Dim femtocellrow As Int32
Dim noreceipt As Int32
Dim username As String
Dim client As String
Dim comName As String
noreceipt = Session("recNo")
username = Session("username")
comName = Session("compName")
'Response.Write("noreceipt" & noreceipt)
cmd.CommandText = "SELECT COUNT(*) AS RETURNCOUNT FROM dbo.tempTable"
intCount = cmd.ExecuteScalar
' Response.Write("count " & intCount)
cmd.CommandText = "SELECT noDevices FROM dbo.Receipt WHERE receiptNo= #noreceipt"
cmd.Parameters.AddWithValue("#noreceipt", noreceipt)
getReceipt = cmd.ExecuteScalar
'Response.Write("receipt " & getReceipt)
cmd.CommandText = "SELECT COUNT(*) AS RETURNCOUNT FROM dbo.femtocell WHERE receiptNo= #norec"
cmd.Parameters.AddWithValue("#norec", noreceipt)
femtocellrow = cmd.ExecuteScalar
'Response.Write("femrow " & femtocellrow)
cmd.CommandText = "SELECT clientID FROM dbo.Receipt WHERE companyName=#comName"
cmd.Parameters.AddWithValue("#comName", comName)
client = cmd.ExecuteScalar
'Response.Write("client " & client)
con.Close()
Dim rowsAffected As Integer = 0
Dim myConnectionString As String = "Data Source=192.168.18.30; User Id=sa;Password=google;Initial Catalog=femtocell;"
Dim myConnection As New SqlConnection(myConnectionString)
If (femtocellrow < getReceipt) & (intCount < femtocellrow) Then
'Dim myQuery As String = "SELECT ([uploadID],[clientID],[receiptNo],[compName],[state],[town],[district],[siteAddress],[latitude],[longitude],[type],[serialNo],[man],[model],[pwr],[appNo],[manAntenna],[modelAntenna],[height],[gain],[emission],[bhaul],[strucType],[covType],[cov],[spectBand],[txFreq],[rxFreq],[bw],[regFee],[uspArea],[commDate],[compName]) INTO dbo.femtocell (username,client,noreceipt,comName,[State],[Town],[District],[Site_Address],[Latitude],[Longitude],[Equipment_Type],[Equipment_Serial_No],[Equipment_Man],[Equipment_Model],[Equipment_Pwr_Mw],[Equipment_App_No],[Antenna_Man],[Antenna_Model],[Antenna_Height_m],[Antenna_Gain_Db],[antenna_emission],[Bhaul],[Struc_Type],[Cov_Type],[Cov_m],[Spect_Band],[Tx_Freq_MHz],[Rx_Freq_MHz],[Bw_KHz],[Reg_Fee_RM],[USP_area],[Comm_Date]) FROM dbo.tempTable"
' Dim myQuery As String = "INSERT INTO dbo.femtocell ([uploadID],[clientID],[receiptNo],[compName],[state],[town],[district],[siteAddress],[latitude],[longitude],[type],[serialNo],[man],[model],[pwr],[appNo],[manAntenna],[modelAntenna],[height],[gain],[emission],[bhaul],[strucType],[covType],[cov],[spectBand],[txFreq],[rxFreq],[bw],[regFee],[uspArea],[commDate],[compName]) VALUES (SELECT 'username','client','noreceipt','comName',[State],[Town],[District],[Site_Address],[Latitude],[Longitude],[Equipment_Type],[Equipment_Serial_No],[Equipment_Man],[Equipment_Model],[Equipment_Pwr_Mw],[Equipment_App_No],[Antenna_Man],[Antenna_Model],[Antenna_Height_m],[Antenna_Gain_Db],[antenna_emission],[Bhaul],[Struc_Type],[Cov_Type],[Cov_m],[Spect_Band],[Tx_Freq_MHz],[Rx_Freq_MHz],[Bw_KHz],[Reg_Fee_RM],[USP_area],[Comm_Date]FROM dbo.tempTable"
Dim myQuery As String = "INSERT INTO dbo.femtocell ([state],[town],[district],[siteAddress],[latitude],[longitude],[type],[serialNo],[man],[model],[pwr],[appNo],[manAntenna],[modelAntenna],[height],[gain],[emission],[bhaul],[strucType],[covType],[cov],[spectBand],[txFreq],[rxFreq],[bw],[regFee],[uspArea],[commDate]) SELECT [State],[Town],[District],[Site_Address],[Latitude],[Longitude],[Equipment_Type],[Equipment_Serial_No],[Equipment_Man],[Equipment_Model],[Equipment_Pwr_Mw],[Equipment_App_No],[Antenna_Man],[Antenna_Model],[Antenna_Height_m],[Antenna_Gain_Db],[antenna_emission],[Bhaul],[Struc_Type],[Cov_Type],[Cov_m],[Spect_Band],[Tx_Freq_MHz],[Rx_Freq_MHz],[Bw_KHz],[Reg_Fee_RM],[USP_area],[Comm_Date]FROM dbo.tempTable"
Dim myCommand As New SqlCommand(myQuery, myConnection)
Try
myConnection.Open()
rowsAffected = myCommand.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
myConnection.Close()
End Try
Else
Dim message As String = "Number of devices submitted is invalid."
Dim sb As New System.Text.StringBuilder()
sb.Append("alert('")
sb.Append(message)
sb.Append("');")
ClientScript.RegisterOnSubmitStatement(Me.GetType(), "alert", sb.ToString())
End If
End Sub
End Class
Maybe one of these will help:
SQL SERVER – Insert Data From One Table to Another Table – INSERT INTO SELECT – SELECT INTO TABLE
sqlauthority.com
copy all rows of a table to another table
stackoverflow.com
C# – Bulk copying data into MS SQL Server with DataTables
myadventuresincoding.wordpress.com