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
Related
I have some TextBox in ItemTemplate. It allow users to edit multiple rows.
'Button1' can update one row. I want to click all of it in one page using a button outside GridView.
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" DataKeyNames="id">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("id") %>' visible="false"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("something") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Update" CommandName="Update"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString='<%$ ConnectionStrings:ApplicationServices%>'
UpdateCommand="...">
</asp:SqlDataSource>
I am looking for some thing like this:
For i = 0 To Me.GridView1.Rows.Count - 1
SqlDataSource1.Update(i) //pseudo
Next
I want to reuse UpdateCommand in SqlDataSource1.
Create an update function or subroutine then call it as you needed. Something like this
Public Function ExecuteNonQuery(ByVal cmd As String, ByVal cmdType As CommandType, Optional ByVal parameters() As SqlParameter = Nothing) As Integer
Dim connection As SqlConnection = Nothing
Dim transaction As SqlTransaction = Nothing
Dim command As SqlCommand = Nothing
Dim res As Integer = -1
Try
connection = New SqlConnection(ConnectionString)
command = New SqlCommand(cmd, connection)
command.CommandType = cmdType
Me.AssignParameters(command, parameters)
connection.Open()
transaction = connection.BeginTransaction()
command.Transaction = transaction
res = command.ExecuteNonQuery()
transaction.Commit()
Catch ex As Exception
If Not (transaction Is Nothing) Then
transaction.Rollback()
End If
Throw New SqlDbException(ex.Message, ex.InnerException)
Finally
If Not (connection Is Nothing) AndAlso (connection.State = ConnectionState.Open) Then connection.Close()
If Not (command Is Nothing) Then command.Dispose()
If Not (transaction Is Nothing) Then transaction.Dispose()
End Try
Return res
End Function
That is a reusable function for executing non-query command.
I just known how to do it. I answer my own question. It works.
.aspx
UpdateCommand="..." //SQL Update Command
<UpdateParameters>
//Some Parameters
</UpdateParameters>
.aspx.vb
For i = 0 To Me.GridView1.Rows.Count - 1
Me.GridView1.UpdateRow(i, True)
Next
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.
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 !
This is my datalist:
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1"
RepeatLayout="Flow">
<ItemTemplate>
<asp:Label ID="IdLabel" runat="server" Text='<%# Eval("ID") %>' Visible="False" />
Titre:
<asp:Label ID="TitreLabel" runat="server" Text='<%# Eval("Titre") %>' />
<br />
Description:
<asp:Label ID="DescriptionLabel" runat="server"
Text='<%# Eval("Description") %>' />
<br />
<asp:Image ID="Image1" runat="server"
ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}") %>' Width="200" Height="200"/>
<br />
comments:
<asp:Label ID="commentsLabel" runat="server" Text='<%# Eval("comments") %>' />
<br />
Ajouter commentaire
<asp:button ID="btnAjouter" runat="server" OnCommand="Button_Command"
CommandName="add" Text="Ajouter" />
<asp:TextBox ID="TextBoxComments" runat="server"></asp:TextBox>
<br/>
<br/>
</ItemTemplate>
</asp:DataList>
This my aspx.vb button event:
Sub Button_Command(ByVal sender As Object, ByVal e As CommandEventArgs)
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("BecsEtMuseauxSQL").ConnectionString
Dim con As SqlConnection = New SqlConnection(connectionString)
con.Open()
Dim cmd As New SqlCommand("updateComments", con)
cmd.CommandType = CommandType.StoredProcedure
//I try this ....
cmd.Parameters.Add("#id", SqlDbType.Int).Value = DataList1.FindControl("IdLabel").ToString()
cmd.Parameters.Add("#Comments", SqlDbType.NVarChar).Value = DataList1.FindControl("TextBoxComments").ToString()
cmd.ExecuteNonQuery()
End Sub
I get an error like this: "The object reference is not definied to an object instance"
How can I catch the value from the label IdLabel and TextBoxComments in this situation?
You should handle the DataList's ItemCommand instead of the Button's Command.
Then you can find your controls with e.Item.FindControl:
Private Sub DataList1_ItemCommand(source As Object, e As System.Web.UI.WebControls.DataListCommandEventArgs) _
Handles DataList1.ItemCommand
If e.CommandName = "add" Then
Dim IdLabel = DirectCast(e.Item.FindControl("IdLabel"), Label)
Dim TextBoxComments = DirectCast(e.Item.FindControl("TextBoxComments"), TextBox)
' ... '
End If
End Sub
on aspx, remove your redundant Command-handler:
<asp:button ID="btnAjouter" CommandName="add" Text="Ajouter" runat="server" />
If you want to use the Button's Click-Event instead, that's possible also.
Protected Sub btnAjouter_Click(sender As Object, e As EventArgs)
Dim container = DirectCast(DirectCast(sender, Control).NamingContainer, DataListItem)
Dim IdLabel = DirectCast(container.FindControl("IdLabel"), Label)
Dim TextBoxComments = DirectCast(container.FindControl("TextBoxComments"), TextBox)
' ... '
End Sub
on aspx, add the click-event handler to the button:
<asp:button ID="btnAjouter" OnClick="btnAjouter_Click" Text="Ajouter" runat="server" />
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.