Procedure not updating the data in the database - asp.net

this is my asp code:
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField HeaderText="Id" InsertVisible="False">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("id") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="firstname">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("firstname") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbl" runat="server" Text='<%# Bind("firstname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
and this is my vb code:
Imports System.Data.SqlClient
Imports System.Data
Partial Class testt
Inherits System.Web.UI.Page
Public connectionString As String = ConfigurationManager.ConnectionStrings("TestConnectionString").ConnectionString
Public cn As SqlConnection = New SqlConnection(connectionString)
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim ds As New DataSet
Dim dt As New DataTable
If cn.State = ConnectionState.Closed Then
cn.Open()
End If
Dim command As SqlCommand = New SqlCommand("selecttest", cn)
command.CommandType = CommandType.StoredProcedure
Dim da As New SqlDataAdapter(command)
da.Fill(ds, "testtt")
dt = ds.Tables(0)
GridView1.DataSource = dt
If Not IsPostBack Then
GridView1.DataBind()
End If
If cn.State = ConnectionState.Open Then
cn.Close()
End If
End Sub
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs) Handles GridView1.RowUpdating
Dim strPersonID As String = DirectCast(GridView1.Rows(e.RowIndex).FindControl("TextBox1"), TextBox).Text
Dim strLastName As String = DirectCast(GridView1.Rows(e.RowIndex).FindControl("TextBox2"), TextBox).Text
Try
Dim command As SqlCommand = New SqlCommand("updatetest", cn)
command.CommandType = CommandType.StoredProcedure
command.Parameters.AddWithValue("#pid", strPersonID)
command.Parameters.AddWithValue("#pfirstname", strLastName)
If cn.State = ConnectionState.Closed Then
cn.Open()
End If
command.ExecuteNonQuery()
MsgBox("1 row updated")
If cn.State = ConnectionState.Open Then
cn.Close()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Public Sub GridView1_RowEditing(sender As Object, e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing
GridView1.EditIndex = e.NewEditIndex
If Not IsPostBack Then
GridView1.DataBind()
End If
End Sub
End Class
1- the columns in the grid is duplicated which means that I'm getting the selected data from the stored procedure and the data binded in the template fields in new columns so instead of getting just 2 columns I'm getting 4 having the same data so how can i fix this?
2-no errors in the rowupdating event everything is working fine but the data is not being updated in the database. Note that the stored procedure is working fine in SQL..
it may be cause because of the duplicated columns mentioned before...
any help??
thank you !

Related

displaying data in asp gridview

I'm having this issue on displaying data into gridview. I want to display data from BindData into a custom made gridview as below. I have already tried
write the code on same page as html > working(but my senior engineer does not want that), so now I need to redo it by use back-end code and pass those (ID,Name,Age) into those label ID using dataset. how can I accomplished this?
<asp:GridView ID="MyGridView" runat="server" CellPadding="5" CssClass="ControlStyle"
ForeColor="#333333" Font-Size="8px" GridLines="Vertical" width="40%" CaptionAlign="Left"
PageSize="15" AllowPaging="True" OnPageIndexChanging="MyData_OnPageIndexChanging"
AutoGenerateColumns="False" enableEventValidation="false">
<Columns >
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:ImageButton ID="img" runat="server" ImageUrl="~/Images/arrow-2a.png" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lbl_ID" runat="server" Font-Size="10px" CssClass="ControlStyleUpperCase"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lbl_Name" runat="server" Font-Size="10px" CssClass="ControlStyleUpperCase"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<asp:Label ID="lbl_Age" runat="server" Font-Size="10px" CssClass="ControlStyleUpperCase"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
and I want to display below data.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not Me.IsPostBack Then
Me.BindData()
End If
End Sub
Private Sub BindData()
Dim sCon As String = "MyConnectionString"
Using con As New SqlConnection(sCon)
Using cmd As New SqlCommand(" select * from users ")
Dim sda As New SqlDataAdapter()
Try
cmd.Connection = con : con.Open()
sda.SelectCommand = cmd
Dim dt As New DataTable
sda.Fill(dt)
'BIND DATABASE WITH THE GRIDVIEW.
MyGridView.DataSource = dt
MyGridView.DataBind()
Catch ex As Exception
txtMsg.Text = ex.Message
End Try
End Using
End Using
End Sub
with above code, my page show nothing, just white canvas, where did I do wrong? please guide.
thanks
Thanks for your kind effort, I've manage to solve this issue by modified my code from this
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not Me.IsPostBack Then
Me.BindData()
End If
End Sub
into this
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindData()
End If
End Sub
I still don't know whats the different between those two but I've manage to get my results as expected.

Why returned value is not being saved in DetailsView?

The null object reference was solved. Now I need the returned value to be saved to the record. Here is the data bound code:
Private Sub dvSMasterCurrentYear_DataBound(sender As Object, e As EventArgs) Handles dvSMasterCurrentYear.DataBound
Dim dv As DetailsView = New DetailsView
dv = dvSMasterCurrentYear
If DetailsViewMode.Insert Then
Dim ctl = dv.FindControl("PlantYear")
If ctl IsNot Nothing Then
DirectCast(dv.FindControl("PlantYear"), TextBox).Text = GetYear()
Else
Throw New Exception("Control was not found")
End If
End If
End Sub
Here is the GetYear function:
Public Function GetYear()
Dim thisDate As Date = Now
Dim thisYear As String
'thisDate = #2/12/1969#
thisYear = Year(thisDate)
Return thisYear
End Function
For inserting I use this :
Private Sub DetailsView1_ItemInserting(sender As Object, e As DetailsViewInsertEventArgs) Handles dvSMasterCurrentYear.ItemInserting
Dim view As DetailsView = DirectCast(sender, DetailsView)
Dim txtYearPlant As TextBox = DirectCast(DirectCast(sender, DetailsView).FindControl("PlantYear"), TextBox)
End Sub
This is what the mark up looks like:
<asp:TemplateField HeaderText="Year Plant (yyyy)*">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("PlantYear") %>'></asp:Label>
<%# Eval("Year")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="PlantYear" runat="server"></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="PlantYear" runat="server" Text='<%# GetYear()%>'></asp:TextBox >
</InsertItemTemplate>
</asp:TemplateField>
Markup looks like:
<asp:TemplateField HeaderText="Year Plant (yyyy)*">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("PlantYear")%>'></asp:Label>
<%# Eval("Year")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="PlantYear" runat="server"></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="PlantYear" runat="server" Text='<%# GetYear()%>'></asp:TextBox >
</InsertItemTemplate>
</asp:TemplateField>
I don't know why the value is not being saved, so how do I fix it?
Thank you for your help.
In Private Sub DetailsView1_ItemInserting event I changed
Dim txtYearPlant As TextBox = DirectCast(DirectCast(sender, DetailsView).FindControl("YearPlant"), TextBox)
TO
Dim txtYearPlant As TextBox = TryCast(view.FindControl("YearPlant"), TextBox)
e.Values.Add("YearPlant", txtYearPlant.Text)
So now the value in the PlantYear textbox is saved to the record.

Refresh GridView1 in UpdatePanel1 after first executing the code in Button1_Click

I would like to update UpdatePanel1 after executing the code in Button1_Click.
UpdatePanel1.Update() is not updating GridView1.
The trigger in UpdatePanel1, I think, is firing immediately after Button1 is pushed instead of after executing the code in the pushbutton event.
I would like to refresh GridView1 in UpdatePanel1 after first executing the code in Button1_Click.
Default.aspx.vb
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
Dim connStr As String = "connection string works"
Dim cmdStr As String = "INSERT INTO [test] ([datetime],[col1],[col2],[col3]) VALUES (#datetime,#col1,#col2,#col3);"
Try
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(cmdStr, conn)
conn.Open()
cmd.Parameters.AddWithValue("#datetime", DateTime.Now)
cmd.Parameters.AddWithValue("#col1", TextBox1.Text)
cmd.Parameters.AddWithValue("#col2", TextBox2.Text)
cmd.Parameters.AddWithValue("#col3", TextBox3.Text)
cmd.ExecuteNonQuery()
conn.Close()
cmd.Dispose()
conn.Dispose()
End Using
End Using
Catch ex As Exception
End Try
UpdatePanel1.Update()
End Sub
Default.aspx
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click"></asp:AsyncPostBackTrigger>
</Triggers>
<ContentTemplate>
<center><table><tr><td align="center">
<asp:Label ID="Label4" runat="server" Text="Column 1"></asp:Label></td><td align="center">
<asp:Label ID="Label5" runat="server" Text="Column 2"></asp:Label></td><td align="center">
<asp:Label ID="Label6" runat="server" Text="Column 3"></asp:Label><br /></td></tr><tr><td align="center">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td><td align="center">
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td><td align="center">
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br /></td></tr><tr><td colspan="3" align="center">
<asp:Button ID="Button1" runat="server" Text="Insert Into Gridview" /></td></tr><tr><td><br />
<asp:GridView ID="GridView1"
DataSourceID="SqlDataSource1"
AutoGenerateColumns="true"
AllowPaging="true"
PageSize="50"
AllowSorting="true"
DataKeyNames="idt"
AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true"
runat="server">
</asp:GridView>
<asp:SqlDataSource
ID="SqlDataSource1"
ConnectionString="<%$ ConnectionStrings:connone %>"
SelectCommand="SELECT * FROM [test];"
DataSourceMode="DataSet"
UpdateCommand="UPDATE test [datetime],[col1],[col2],[col3] SET #datetime, #col1, #col2, #col3;"
DeleteCommand="DELETE FROM [test] WHERE [idt]=#idt;"
runat="server">
</asp:SqlDataSource>
</td></tr></table></center>
</ContentTemplate>
</asp:UpdatePanel>
You don't need to call UpdatePanel1.Update() in your Button1_Click method since Button1 is a trigger for your UpdatePanel. Instead you must call GridView1.DataBind() to refetch data from DB, like this :
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
Dim connStr As String = "connection string works"
Dim cmdStr As String = "INSERT INTO [test] ([datetime],[col1],[col2],[col3]) VALUES (#datetime,#col1,#col2,#col3);"
Try
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(cmdStr, conn)
conn.Open()
cmd.Parameters.AddWithValue("#datetime", DateTime.Now)
cmd.Parameters.AddWithValue("#col1", TextBox1.Text)
cmd.Parameters.AddWithValue("#col2", TextBox2.Text)
cmd.Parameters.AddWithValue("#col3", TextBox3.Text)
cmd.ExecuteNonQuery()
conn.Close()
cmd.Dispose()
conn.Dispose()
End Using
End Using
Catch ex As Exception
End Try
GridView1.Databind()
End Sub

How to Update dataset and backend sql table from Gridview data without for loop?

In ASP.NET i have GridView as
<asp:GridView ID="GV" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%#Eval("Name") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="EmailId" HeaderText="Email" />
</Columns>
</asp:GridView>
<asp:Button ID="btnSubmit" runat="server" Text="Update Changes to Dataset" />
here is my code behind to bind the data on page load
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim str As String = ConfigurationManager.ConnectionStrings("DBCon").ConnectionString
Dim Conn As New SqlConnection(str)
Conn.Open()
Dim qry As String = "SELECT Name,EmailId FROM dbo.Employee"
Dim adp As New SqlDataAdapter(qry, Conn)
Dim ds As New DataSet
adp.Fill(ds)
GV.DataSource = ds
GV.DataBind()
End If
End Sub
Now in my Gridview i have bind Name to Textbox and those textboxes are editable for client
I have plenty of records to show on gridview
Now what i want is that on a click of submit button updated data to be appeared in a dataset without using any kind of for loop
And i also want the updated data to be reflected at backend Employee table
Suggest if you have any tricks

regarding an sql query error

here is my admin.aspx.vb
Imports System.Data.SqlClient
Partial Class Admin
Inherits System.Web.UI.Page
Dim conn As New SqlConnection("Data Source=CHIRAG-PC;Initial Catalog=car;Integrated Security=True")
Dim cmd As SqlCommand
Dim drd As SqlDataReader
Dim adp As SqlDataAdapter
Dim y As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.SelectedIndexChanged
Dim x As Integer
x = GridView1.SelectedIndex
y = GridView1.Rows(x).Cells(1).Text
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
str = "update carHeader set cartype='" + car.Text.ToString() + "',imagefile='" + img.Text + "',capacity=" + cap.Text + "where id=" + Convert.ToDouble(y)
conn.Open()
cmd = New SqlCommand(str, conn)
cmd.ExecuteNonQuery()
conn.Close()
End Sub
End Class
and its admin.aspx
<%# Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="Admin.aspx.vb" Inherits="Admin" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
<br />
<br />
</asp:Content>
<asp:Content ID="Content2" runat="server" contentplaceholderid="MainContent">
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Data Source=CHIRAG-PC;Initial Catalog=car;Integrated Security=True"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT * FROM [carHeader] ORDER BY [id]"></asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" Height="149px" Width="267px">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="id" HeaderText="id"
SortExpression="id" />
<asp:BoundField DataField="cartype" HeaderText="cartype"
SortExpression="cartype" />
<asp:BoundField DataField="imagefile" HeaderText="imagefile"
SortExpression="imagefile" />
<asp:BoundField DataField="capacity" HeaderText="capacity"
SortExpression="capacity" />
</Columns>
</asp:GridView>
<asp:Panel ID="Panel1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Image file"></asp:Label>
<asp:TextBox ID="img" runat="server"></asp:TextBox>
<asp:Label ID="Label2" runat="server" Text="Car Type"></asp:Label>
<asp:TextBox ID="car" runat="server"></asp:TextBox>
<asp:Label ID="Label3" runat="server" Text="capacity"></asp:Label>
<asp:TextBox ID="cap" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Save" />
</asp:Panel>
</asp:Content>
getting an error in sql query regarding its update statement
and table contents are of carHeader:
cartype varchar ,id int,imagefile varchar,capacity int
... + cap.Text + "where ...
Notice the lack of a space before where. It's probably producing a statement like:
... field = valuewhere ...
This would break the SQL.
Additionally, it's bad practice to use string concatenation in SQL statements like this, both from a security and performance point of view. You'll want to look into using parameterized queries.
Edit: Based on your comment here:
its givin me error conversion from update set cartype=....to double type is not valid
It sounds like the error is referring to this part of the query:
set cartype='" + car.Text.ToString() + "'
What type is cartype? According to the error message, it's a double. But according to your query, you're trying to set it to a string value (by wrapping it in single quotes). If it's a double then it needs to be a numeric value, not a string.

Resources