I'm a new member here. I want to ask something. Best regards for everyone of you to answer my questions. Sorry for my bad English. I'm from Indonesia.
I have two radiobutton, two textbox, two datagridview and one button. The scenario is my first textbox is Input by InvoiceNumber and the second Textbox input by AccountNumber. My question is when I input by Invoicenumber and I click Button Search the datagridview for Invoicenumber will show and when I input by Accountnumber the datagridview for Accounrnumber will show. This is my Code:
Default.aspx.vb: (Updated below to display code correctly by Piyush Khatri)
Protected Sub Submit_Click(sender As Object, e As EventArgs) Handles Submit.Click
periode = cbbulan.SelectedValue.ToString + Microsoft.VisualBasic.Right(cbtahun.Text, 2).ToString
If txtseacrh.Text Then
Me.BindGrid(txtseacrh.Text, periode)
tampildata()
Label3.Text = "Consignee : "
Label4.Text = "Address : "
Label5.Text = "Product :"
End If
Me.BindGrid2(txtsearch2.Text)
End Sub
Private Sub BindGrid(RefNo As String, periode As String)
Dim constr As String = ConfigurationManager.ConnectionStrings("dbCon").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand()
cmd.CommandText = "Declare #awb As varchar(50)
Select #awb=awb from msdetail md inner join msdata mt On mt.PuNo=md.Puno
where md.Puno='" & RefNo & "'
Select '1' as no, Convert(varchar(12), pudate, 103) As Date,CONVERT(varchar(8), pudate,8) as time,'PU' AS status,'' as Recipient, '' as Remaks,'' as PIC from MsDetail where AWB=#awb
And Periode='" & periode & "'
union
Select '2' as no, CONVERT(varchar(12),pudatein,103) as date,CONVERT(varchar(8), pudatein,8) as time,'DE' AS status,'' as Recipient, '' as Remaks, IdUser as PIC from MsDetail where AWB=#awb
And Periode='" & periode & "'
UNION
Select '3' as no, CONVERT(varchar(12),stdate,103) as date,CONVERT(varchar(8), stdate,8) as time,StStt AS status,StPenerima as Recipient,StRel as Remaks, st.IdUser as PIC from status st
inner Join MsDetail md on md.AWB=st.AWB where md.AWB=#awb And Periode='" & periode & "' order by no"
cmd.Connection = con
Dim dt As New DataTable()
Using sda As New SqlDataAdapter(cmd)
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
End Sub
Private Sub BindGrid2(Puno As String)
Dim constr As String = ConfigurationManager.ConnectionStrings("dbCon").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand()
cmd.CommandText = "select Refno,Field1,(CONVERT (varchar(10),PuDate,103)) as PuDate,(Convert (varchar(10),Pudatein,103))as Pudatein,mdcompany,MdAdd1,mdadd2,mdadd3,mdadd4,StStt,(CONVERT (varchar(10),StDate,103)) as StDate,StPenerima,StRel from MsDetail inner join MsData on MsDetail.PuNo=MsData.PuNo
left join Status on MsDetail.AWB=Status.AWB where MsData.Refno='" & Puno & "'"
cmd.Connection = con
Dim dt As New DataTable()
Using sda As New SqlDataAdapter(cmd)
sda.Fill(dt)
GridView2.DataSource = dt
GridView2.DataBind()
End Using
End Using
End Using
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
'Fill Years
For i As Integer = Year(Now) - 1 To Year(Now)
cbtahun.Items.Add(i.ToString())
Next
cbtahun.Items.FindByValue(System.DateTime.Now.Year.ToString()).Selected = True 'set current year as selected
End If
End Sub
Protected Sub cbbulan_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbbulan.SelectedIndexChanged
'Session["cbbulan"]=DropDownList.SelectedValue;
End Sub
Private Sub koneksi()
strconn = WebConfigurationManager.ConnectionStrings("dbCon").ConnectionString
MyCn = New SqlConnection(strconn)
If MyCn.State <> Data.ConnectionState.Closed Then MyCn.Close()
MyCn.Open()
End Sub
Private Sub tampildata()
koneksi()
Dim sql As String
Dim cmd As SqlCommand
Dim dread As SqlDataReader
' Dim constr As String = ConfigurationManager.ConnectionStrings("a").ConnectionString
sql = "select prname,MdName,isnull(MdAdd1,'') + ' ' + isnull(MdAdd2,'') + ' ' + isnull(MdAdd3,'') as ALAMAT from MsData inner join MsDetail on MsDetail.PuNo=MsData.PuNo
Left Join Produk on MsDetail.Code=Produk.Code where msdata.PuNo='" & txtseacrh.Text & "'"
cmd = New SqlCommand(Sql, MyCn)
dread = cmd.ExecuteReader
If dread.HasRows Then
While dread.Read = True
Label1.Text = dread.Item("mdName").ToString
Label2.Text = dread.Item("ALAMAT").ToString
Label6.Text = dread.Item("PrName").ToString
End While
dread.Close()
End If
End Sub
Try something like this
HTML Code (.aspx page)
<div>
<asp:TextBox ID="txtInvoice" runat="server" />
<asp:TextBox ID="txtAccountNo" runat="server" />
<asp:Button id="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</div>
<div>
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="true" />
</div>
**Code Behind**
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtInvoice.Text.Trim())) {
gv.DataSource = getInvoiceDetails(txtInvoice.Text);
gv.DataBind();
}
else if (!string.IsNullOrEmpty(txtAccountNo.Text.Trim()))
{
gv.DataSource = getAccountDetails(txtInvoice.Text);
gv.DataBind();
}
}
private DataTable getInvoiceDetails(string invoiceNo) {
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString)) {
using (SqlCommand cmd = new SqlCommand("YourQueryToGetInvoiceDetails")) {
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
return dt;
}
}
}
private DataTable getAccountDetails(string invoiceNo)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("YourQueryToGetAmountDetails"))
{
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
return dt;
}
}
}
Related
I'm trying to make fb login for my website. So I put condition if user already exist then it will do login & if not then it perform insert user data.
In following code if string is Not Null Or Empty then I am trying to execute code but by putting breakpoint on my statement I see that if string has value then rest code not executing. What could be the reason? Is I am doing something wrong? My first block of code is working fine(users data fetching from facebook). Problem is in second block where I am checking condition.
Private Sub login_Load(sender As Object, e As EventArgs) Handles Me.Load
FaceBookConnect.API_Key = "XXXXXXX"
FaceBookConnect.API_Secret = "XXXXXXX"
If Not IsPostBack Then
If Request.QueryString("error") = "access_denied" Then
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('User has denied access.')", True)
Return
End If
Dim code As String = Request.QueryString("code")
If Not String.IsNullOrEmpty(code) Then
Dim data As String = FaceBookConnect.Fetch(code, "me")
Dim faceBookUser As FaceBookUser = New JavaScriptSerializer().Deserialize(Of FaceBookUser)(data)
faceBookUser.PictureUrl = String.Format("https://graph.facebook.com/{0}/picture", faceBookUser.Id)
pnlFaceBookUser.Visible = True
lblId.Text = faceBookUser.Id
lblUserName.Text = faceBookUser.UserName
lblName.Text = faceBookUser.Name
lblEmail.Text = faceBookUser.Email
ProfileImage.ImageUrl = faceBookUser.PictureUrl
btnLogin.Enabled = False
End If
End If
If IsPostBack Then
If Not String.IsNullOrEmpty(lblId.Text) Then
Dim query As String = "Select ID, email From users where ID=#id"
con.Open()
Dim cmd As New MySqlCommand(query, con)
cmd.CommandTimeout = 50000
cmd.Parameters.AddWithValue("#id", lblId.Text)
Dim dr As MySqlDataReader = cmd.ExecuteReader()
If dr.HasRows Then
'Do Login Code here
Try
Dim str As String = "select * from users where ID='" + lblId.Text + "';"
Dim cmd2 As New MySqlCommand(str, con)
Dim da As New MySqlDataAdapter(cmd2)
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
Response.Write("User Already Exist")
Catch ex As Exception
Response.Write(ex)
End Try
Else
Try
Dim str1 As String = "INSERT INTO users (ID, DP, displayName) values('" + lblId.Text + "', '" + ProfileImage.ImageUrl.ToString + "', '" + lblName.Text + "')"
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
dr.Close()
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
command.ExecuteNonQuery()
Response.Write("User Added")
Catch ex As Exception
Response.Write(ex)
End Try
End If
con.Close()
End If
End If
End Sub
End Class
I'm kinda new to asp.net but I'm learning fast, tho I cant find any good web forms tutorial for login page written in vb, I'm using the offline application tutorials to learn and I just change the commands,
So i've come to a simple error for you guys, the problem is with the dsc.sqlclient, probably there's not such command, but what should I use?
Thanks a lot anyway!
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=LoginDB;Integrated Security=True")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From Users Where Username='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
Dim dsc As New SqlClient.SqlCommand(strSQL, conn)
' Fill the dataset
Dim ds As New DataSet()
dsc.sqlclient.sqlcommand(ds, "Users")
' if there no entry then the user is invalid
If ds.Tables("Users").Rows.Count = 0 Then
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
End If
End Sub
Thanks a lot guys, this is the correct answer tho, kbworkshop helped me a lot!
For anyone wanna know this is the code
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=LoginDB;Integrated Security=True")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From Users Where Username='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
'I recommend not to use * in querys
Dim dsc As New SqlClient.SqlCommand(strSQL, conn)
conn.Open()
Dim dr As SqlDataReader
dr = dsc.ExecuteReader()
If dr.HasRows = True Then
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
conn.Close()
End If
End Sub
Your code should be something like this:
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=LoginDB;Integrated Security=True")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From Users Where Username='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
objConn.Open()
' Fill the dataset
Dim ds As New DataSet("Users")
Dim daExample As New SqlDataAdapter(strSQL, objConn)
daExample.Fill(ds, "Users2")
' if there no entry then the user is invalid
If ds.Tables("Users").Rows.Count = 0 Then
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
objConn.close()
End If
End Sub
but you can also take this:
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=LoginDB;Integrated Security=True")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From Users Where Username='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
'I recommend not to use * in querys
Dim dsc As New SqlClient.SqlCommand(strSQL, conn)
Dim dr As SqlDataReader
dr = dsc.ExecuteReader()
If dr.HasRows = True Then
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
End If
End Sub
PLEASE don't create your SELECT statement by pasting text together.
Ugh.
Never do that.
You just allow anyone to use "SQL Injection" to log in (and worse) without a
password.
Imports System.Data
Imports System.Data.SqlClient
Partial Class log
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=F:\WebSite1\App_Data\Database.mdf;Integrated Security=True;User Instance=True")
Dim log As String = "SELECT * FROM login WHERE userid='" & TextBox1.Text & "' AND password='" & TextBox2.Text & "'"
Session("user") = TextBox1.Text
Dim cmd As New SqlCommand(log, cn)
Dim dr As SqlDataReader
cn.Open()
dr = cmd.ExecuteReader()
If dr.HasRows = True Then
Response.Redirect("showdata.aspx")
Else
Response.Redirect("log.aspx")
End If
End Sub
End Class
You can use SqlDataAdapter class to fill your dataset:
SqlConnection conn = new SqlConnection("My ConnectionString");
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = SQL;
da.SelectCommand = cmd;
DataSet ds = new DataSet();
conn.Open();
da.Fill(ds);
conn.Close();
VB.Net:
Dim conn As New SqlConnection("My ConnectionString")
Dim da As New SqlDataAdapter()
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = SQL
da.SelectCommand = cmd
Dim ds As New DataSet()
conn.Open()
da.Fill(ds)
conn.Close()
I have a SQL Server table with 5 columns. col1 is the primary key. I an working in ASP.net 4.0.
I want to be able to edit and update my SQL Server table with the edit and update respectively.
I am having a little trouble with the update. Here is my code:
<asp:GridView ID="GridView1" runat="server" AutoPostBack="True" AutoGenerateColumns="True" AutoGenerateEditButton="True" OnRowEditing="Gridview1_OnRowEditing" OnRowUpdating="GridView1_OnRowUpdating">
</asp:GridView>
Code:
Sub ShowGrid()
Dim connStr, cmdStr As String
connStr = "connection string works"
cmdStr = "SELECT * FROM table1;"
Dim MyDataSet As New DataSet
Dim MyDataTable As New DataTable()
Try
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(cmdStr, conn)
conn.Open()
cmd.ExecuteNonQuery()
Using MyDataAdaptor As New SqlDataAdapter(cmd)
MyDataAdaptor.Fill(MyDataSet)
MyDataTable = MyDataSet.Tables(0)
GridView1.EditIndex = Convert.ToInt32(ViewState("edit"))
GridView1.DataSource = MyDataTable
GridView1.DataBind()
End Using
conn.Close()
cmd.Dispose()
conn.Dispose()
End Using
End Using
Catch ex As Exception
Throw ex
End Try
End Sub
Protected Sub GridView1_OnRowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
ViewState("edit") = GridView1.EditIndex
ShowGrid()
End Sub
Protected Sub GridView1_OnRowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
Dim connStr, cmdStr As String
connStr = "connection string works"
cmdStr = "UPDATE table1 SET (col2=#col2,col3=#col3,col4=#col4,col5=#col5) WHERE col1=#col1;"
Try
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(cmdStr, conn)
conn.Open()
cmd.Parameters.AddWithValue("#col1", GridView1.Rows(e.RowIndex).Cells(0).Text)
cmd.Parameters.AddWithValue("#col2", GridView1.Rows(e.RowIndex).Cells(1).Text)
cmd.Parameters.AddWithValue("#col3", GridView1.Rows(e.RowIndex).Cells(2).Text)
cmd.Parameters.AddWithValue("#col4", GridView1.Rows(e.RowIndex).Cells(3).Text)
cmd.Parameters.AddWithValue("#col5", GridView1.Rows(e.RowIndex).Cells(4).Text)
cmd.ExecuteNonQuery()
conn.Close()
cmd.Dispose()
conn.Dispose()
End Using
End Using
Catch ex As Exception
End Try
ViewState("edit") = e.RowIndex
ShowGrid()
End Sub
I'm trying to download files from an SQL Server 2012 database using GridView. I am getting an ArgumentOutOfRangeException giving me this error:
Index was out of range. Must be non-negative and less than the size of the collection.
on:
Dim fileid As Integer = Convert.ToInt32(GridView1.DataKeys(gvrow.RowIndex).Value.ToString())
Code concerned:
Protected Sub lnkDownload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim lnkbtn As LinkButton = TryCast(sender, LinkButton)
Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)
Dim fileid As Integer = Convert.ToInt32(GridView1.DataKeys(gvrow.RowIndex).Value.ToString())
Dim name As String, type As String
Dim con As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True;")
con.Open()
Using cmd As New SqlCommand()
cmd.CommandText = "Select content_name, content_type, content_file from content where content_id=#Id"
cmd.Parameters.AddWithValue("#Id", fileid)
cmd.Connection = con
con.Open()
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
download(dt)
End If
End Using
End Sub
Public Function GetData(ByVal cmd As SqlCommand) As DataTable
Dim dt As New DataTable
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnStringDb1").ConnectionString()
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
Return dt
Catch ex As Exception
Response.Write(ex.Message)
Return Nothing
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Function
Protected Sub download(ByVal dt As DataTable)
Dim bytes() As Byte = CType(dt.Rows(0)("Data"), Byte())
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "attachment;filename=" & dt.Rows(0)("Name").ToString())
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End Sub
gvrow.RowIndex at time of debugging is 0.
Full Code:
Imports System.Data.SqlClient
Imports System.Data
Imports System.IO
Partial Class Documents
Inherits System.Web.UI.Page
Protected Sub btnUploadContent_Click(sender As Object, e As EventArgs) Handles btnUploadContent.Click
Dim filePath As String = FileUpload.PostedFile.FileName
Dim filename As String = Path.GetFileName(filePath)
Dim ext As String = Path.GetExtension(filename)
Dim contenttype As String = String.Empty
Select Case ext
Case ".doc"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".docx"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".xls"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".xlsx"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".jpg"
contenttype = "image/jpg"
Exit Select
Case ".png"
contenttype = "image/png"
Exit Select
Case ".gif"
contenttype = "image/gif"
Exit Select
Case ".pdf"
contenttype = "application/pdf"
Exit Select
End Select
If contenttype <> String.Empty Then
Dim fs As Stream = FileUpload.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(fs.Length)
'insert the file into database
Dim strQuery As String = "INSERT INTO [master_db].[dbo].[content] ([content_name],[content_type],[content_file]) VALUES (#Name, #ContentType, #Data)"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value() = contenttype
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes
InsertUpdateData(cmd)
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Text = "File Uploaded Successfully"
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File format not recognised." + " Upload Image/Word/PDF/Excel formats"
End If
End Sub
Protected Sub lnkDownload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim lnkbtn As LinkButton = TryCast(sender, LinkButton)
Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)
Dim fileid As Integer = Convert.ToInt32(GridView1.DataKeys(gvrow.RowIndex).Value.ToString())
Dim name As String, type As String
Dim con As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True;")
con.Open()
Using cmd As New SqlCommand()
cmd.CommandText = "Select content_name, content_type, content_file from content where content_id=#Id"
cmd.Parameters.AddWithValue("#Id", fileid)
cmd.Connection = con
con.Open()
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
download(dt)
End If
End Using
End Sub
Public Function GetData(ByVal cmd As SqlCommand) As DataTable
Dim dt As New DataTable
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnStringDb1").ConnectionString()
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
Return dt
Catch ex As Exception
Response.Write(ex.Message)
Return Nothing
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Function
Protected Sub download(ByVal dt As DataTable)
Dim bytes() As Byte = CType(dt.Rows(0)("Data"), Byte())
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "attachment;filename=" & dt.Rows(0)("Name").ToString())
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End Sub
Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnStringDb1").ConnectionString()
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True;")
cmd.CommandType = CommandType.Text
cmd.Connection = conn
Try
conn.Open()
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Response.Write(ex.Message)
Return False
Finally
conn.Close()
conn.Dispose()
End Try
End Function
End Class
What is happening and why?
replace the error line with this:
Dim selectedRow As Integer = Me.GridView1.CurrentRow.Index
Dim fileid As Integer = Convert.ToInt32(Me.GridView1.Item(1,gvrow.RowIndex).Value.ToString())
Replace the number 1 with the index of the cell that contains the fileid (ie if its the 0 for the first cell, 1 for the second and so on)
Let me know if this works. Am a C# developer so conversions may differ.
pass the RowIndex via CommandArgument and use it to retrieve the DataKey value
add the below line on Button
CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
and add the below line on Server Event
Dim Index As Integer = Integer.Parse(e.CommandArgument.ToString())
Dim val As String = DirectCast(Me.grid.DataKeys(Index)("YourDataKeyName"), String)
Update:
See this samples :
sample1
sample 2
I ran into this a while ago myself replacing a predecessors data adapter's with data readers for obvious reasons.
My fix was simple:
if (dt.Rows.Count == 0)
//do stuff
else
//do nothing
GV.DataSource = new DataTable();
you're also loading with a datatable, so that should make deploying it easier.
The reason in your specific case is the exception is thrown when no data is passed to the GV.
What is the problem in my this code?
The code is working fine but when i enter new record in table and refresh the page then the changes will not be reflected...
what was the problem iam confused..
Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
Dim ds As New DataSet()
Dim connStr As String = "Data Source=DOBRIYAL-PC;Initial Catalog=MenuDb;Integrated Security=True"
Using conn As New SqlConnection(connStr)
Dim sql As String = "Select MenuID, Text, Description, ParentID from Menu"
Dim da As New SqlDataAdapter(sql, conn)
da.Fill(ds)
da.Dispose()
da.AcceptChangesDuringFill = True
End Using
ds.DataSetName = "Menus"
ds.Tables(0).TableName = "Menu"
ds.GetChanges()
Dim relation As New DataRelation("ParentChild", ds.Tables("Menu").Columns("MenuID"), ds.Tables("Menu").Columns("ParentID"), True)
relation.Nested = True
ds.Relations.Add(relation)
XmlDataSource1.Data = ds.GetXml()
If Request.Params("Sel") IsNot Nothing Then
Page.Controls.Add(New System.Web.UI.LiteralControl("You selected " + Request.Params("Sel")))
End If
XmlDataSource1.DataBind()
RadMenu1.DataBind()
End Sub
I have refatored your source code now you should see your new records on page load
Private Sub BindData()
Dim ds As New DataSet()
Dim connStr As String = "Data Source=DOBRIYAL-PC;Initial Catalog=MenuDb;Integrated Security=True"
Using conn As New SqlConnection(connStr)
Dim sql As String = "Select MenuID, Text, Description, ParentID from Menu"
Dim da As New SqlDataAdapter(sql, conn)
da.Fill(ds)
da.Dispose()
da.AcceptChangesDuringFill = True
End Using
ds.DataSetName = "Menus"
ds.Tables(0).TableName = "Menu"
ds.GetChanges()
Dim relation As New DataRelation("ParentChild", ds.Tables("Menu").Columns("MenuID"), ds.Tables("Menu").Columns("ParentID"), True)
relation.Nested = True
ds.Relations.Add(relation)
XmlDataSource1.Data = ds.GetXml()
If Request.Params("Sel") IsNot Nothing Then
Page.Controls.Add(New System.Web.UI.LiteralControl("You selected " + Request.Params("Sel")))
End If
XmlDataSource1.DataBind()
RadMenu1.DataBind()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.BindData()
End Sub