I have two GridView(SalesGView and ProdGView). SalesGView contains dropdowlist and textboxes.ProdGView is wrapped with ModalPopup and is populated by dropdownlist selection from ProdGView.
The issue is when i click button select on ProdGView, the dropdownlist in the SalesGView resets to default value (Electronics) instead of selected value.
I need help on how to correct this issue.
aspx code:
SalesGView Dropdownlist
<asp:DropDownList ID="CatCode" OnSelectedIndexChanged ="CatCode_SelectedIndexChanged" AutoPostBack="true" runat="server" />
ProdGView SelectRow
<asp:GridView ID="ProdGView" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnSelect" Text="Select" runat="server" OnClick="SelectRow" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:
Private Sub SalesGView_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles SalesGView.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
Dim ctrl As Control = e.Row.FindControl("CatCode")
If (Not (ctrl) Is Nothing) Then
Dim dd As DropDownList = CType(ctrl, DropDownList)
Dim connStr As String = ConfigurationManager.ConnectionStrings("SY_InventoryConnectionString").ConnectionString
Dim sqlda As SqlDataAdapter = New SqlDataAdapter
Dim com As SqlCommand = New SqlCommand
Dim dt As DataTable
Dim conn As SqlConnection = New SqlConnection(connStr)
dt = New DataTable
com.Connection = conn
com.CommandText = "SELECT CatName FROM Prod_Category"
sqlda = New SqlDataAdapter(com)
sqlda.Fill(dt)
dd.DataTextField = "CatName"
dd.DataValueField = "CatName"
dd.DataSource = dt
dd.DataBind()
End If
End If
Dim lb As DropDownList = TryCast(e.Row.FindControl("CatCode"), DropDownList)
ScriptManager.GetCurrent(Me).RegisterAsyncPostBackControl(lb)
End Sub
Protected Sub CatCode_SelectedIndexChanged(sender As Object, e As EventArgs)
Me.ModalPopupExtender1.Show()
BindProdGrid()
End Sub
Protected Sub SelectRow(sender As Object, e As EventArgs)
Dim dt As New DataTable()
If ViewState("DataTable") Is Nothing Then
dt = New DataTable()
dt.Columns.AddRange(New DataColumn(1) {New DataColumn("Column2"), New DataColumn("Column4", GetType(String))})
Else
dt = DirectCast(ViewState("DataTable"), DataTable)
End If
Dim row As GridViewRow = TryCast(TryCast(sender, Button).NamingContainer, GridViewRow)
Dim desc As String = row.Cells(2).Text
Dim price As String = row.Cells(3).Text
dt.Rows.Add(desc, price)
Me.SalesGView.DataSource = dt
Me.SalesGView.DataBind()
ViewState("DataTable") = dt
End Sub
Private Sub BindProdGrid()
Dim conString As String = ConfigurationManager.ConnectionStrings("SY_InventoryConnectionString").ConnectionString
Dim rowIndex As Integer = 0
Dim catname As DropDownList = CType(SalesGView.Rows(rowIndex).Cells(1).FindControl("CatCode"), DropDownList)
Using con As New SqlConnection(conString)
Using cmd As New SqlCommand("select Product.CatID,Product.PName,Product.PDesc, " _
& " Product_Details.USP, Prod_Category.CatName " _
& " from Product inner join Product_Details on Product.CatID= Product_Details.CatID " _
& " inner join Prod_Category on Product_Details.CatID=Prod_Category.CatID where Prod_Category.CatName='" & (catname.SelectedItem.Text) & "' ")
Using sda As New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Dim dt As New DataTable()
sda.Fill(dt)
Me.ProdGView.DataSource = dt
Me.ProdGView.DataBind()
End Using
End Using
End Using
End Sub
Related
SOLUTION FOR FUTURE REFERENCE
Problem was the "tecnico" variable that became 0 at every postback, also to avoid any problem I get rid of global variables data1 and data2 and moved them inside the Bindrepeater routine, like this:
Dim data1, data2 As DateTime
If Len(ViewState("dataDa")) = 0 Then
data1 = GetDayFromWeek(Date.Today, DayOfWeek.Monday)
data2 = GetDayFromWeek(Date.Today, DayOfWeek.Sunday)
ViewState("dataDa") = data1
ViewState("dataA") = data2
Else
data1 = Date.ParseExact(ViewState("dataDa"), "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
data2 = Date.ParseExact(ViewState("dataA"), "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
End If
ORIGINAL QUESTION
I'm having trouble with databind of a repeater on page load. I would make a sort of weekly calendar, so the repeater should show dates and for every day a nested repeater should show appointments. I made a simple week selector with a Previous/Next button to move through weeks. It work fine on first page load, but it shows nothing when I use the buttons to change active week.
I know the problem is the postback for sure, but I can't get around this... any help?
html:
<div id="divCalendario" class="panel" runat="Server">
<div id="divCalendarNavigator" style="display: block;" runat="server">
<div>
<%--<asp:Calendar runat="server" ID="calendar" SelectionMode="DayWeek" TitleStyle-ForeColor="#1f7872" TitleStyle-Font-Bold="true" PrevMonthText="<i class=icon-foo></i>" NextMonthText="<i class=icon-foo></i>" NextPrevStyle-Font-Names="FontAwesome" SelectWeekText="<i class=icon-foo></i>" SelectorStyle-Font-Names="FontAwesome" WeekendDayStyle-BackColor="LightGray" SelectedDayStyle-BackColor="#f3ef98" SelectedDayStyle-ForeColor="Black" SelectedDayStyle-Font-Bold="true" OnSelectionChanged="calendar_SelectionChanged"></asp:Calendar>--%>
<asp:LinkButton runat="server" ID="lnkPrevWeek" OnClick="lnkPrevWeek_Click"><i class="fa fa-arrow-circle-o-left" aria-hidden="true"></i></asp:LinkButton>
<asp:Literal ID="litData" runat="server"></asp:Literal>
<asp:LinkButton runat="server" ID="lnkNextWeek" OnClick="lnkNextWeek_Click"><i class="fa fa-arrow-circle-o-right" aria-hidden="true"></i></asp:LinkButton>
<asp:HiddenField runat="server" ID="hdnDa" /><asp:HiddenField runat="server" ID="hdnA" /><asp:HiddenField runat="server" ID="hdnSpostamento"/>
<asp:DropDownList ID="ddlTecnicoCal" runat="server" AppendDataBoundItems="true" CssClass="tendina" placeholder="Tecnico" AutoPostBack="true">
<%--<asp:ListItem Value="-1">Tutti</asp:ListItem>--%>
</asp:DropDownList>
</div>
</div>
<asp:Repeater ID="rptParent" runat="server">
<ItemTemplate>
<p style="margin-left: 10px"><b>
<asp:Label ID="lblDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "data", "{0:dd/MM/yyyy}")%>'></asp:Label></b></p>
<asp:Repeater ID="rptAppuntamenti" runat="server">
<ItemTemplate>
<%# Eval("id")%></td>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
</div>
CODE:
Imports System.Data.SqlClient
Imports System.Globalization
Public Class Calendario
Inherits System.Web.UI.Page
Dim data1, data2 As DateTime
Dim tecnico As Integer
Dim utente As Utenti
Public Function GetDayFromWeek(week As DateTime, day As DayOfWeek) As DateTime
Dim startDay As DayOfWeek = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek
' get the beginning of the week
Dim diff As Integer = CInt(week.DayOfWeek) - CInt(startDay)
Dim beginingOfWeek As DateTime = week.AddDays(diff * -1)
' get the day we are looking for
diff = CInt(day) - CInt(startDay)
If diff < 0 Then
diff = 7 - CInt(startDay)
End If
Return beginingOfWeek.AddDays(diff)
End Function
Public Function datasql(ByVal dataini As Date) As String
Return dataini.Year & "-" & dataini.Month & "-" & dataini.Day
End Function
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
caricaTecnici()
Dim monday = GetDayFromWeek(Date.Today, DayOfWeek.Monday)
Dim sunday = GetDayFromWeek(Date.Today, DayOfWeek.Sunday)
hdnDa.Value = monday
hdnA.Value = sunday
litData.Text = monday & " " & sunday
Dim dbVulcano As New dbVulcanoEntities
data1 = Date.ParseExact(monday, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
data2 = Date.ParseExact(sunday, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
tecnico = Session("idUtente")
utente = dbVulcano.Utenti.Where(Function(u) u.IDUtente = tecnico).Single
End If
BindRepeater()
End Sub
Private Sub BindRepeater()
Dim constr As String = ConfigurationManager.ConnectionStrings("dbVulcanoConnectionString").ConnectionString
Dim query As String = "Select distinct(statoRic.DataAss) as data
From StatoRic
INNER Join
(Richieste INNER JOIN Clienti
On clienti.IDCliente=Richieste.RFCliente)
On StatoRic.RFRic=Richieste.IDRic
join Utenti
On utenti.IDUtente=StatoRic.RFTecnico
WHERE(RFStato = 11 or RFStato = 12 Or rfstato = 13 Or rfstato = 41) And Attuale=1 and StatoRic.DataAss is not null and statoric.DataAss between #data1 and #data2 And RFTecnico=#tecnico
group by statoRic.DataAss order by statoRic.DataAss asc"
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(query, con)
cmd.Parameters.AddWithValue("#data1", data1)
cmd.Parameters.AddWithValue("#data2", data2)
cmd.Parameters.AddWithValue("#tecnico", tecnico)
Using sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
rptParent.DataSource = dt
rptParent.DataBind()
End Using
End Using
End Using
End Sub
Private Sub rptParent_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles rptParent.ItemDataBound
If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim childRepeater As Repeater = e.Item.FindControl("rptAppuntamenti")
Dim lblDate As Label = e.Item.FindControl("lblDate")
'Dim lblTecnico As Label = e.Item.FindControl("lblTecnico")
Dim data As DateTime = Date.ParseExact(lblDate.Text, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
'lblTecnico.Text = utente.NomeExt
Dim constr As String = ConfigurationManager.ConnectionStrings("dbVulcanoConnectionString").ConnectionString
Dim query As String = "Select statoric.id, (case when clienti.IDCliente = 796 then richieste.descr else clienti.RagSociale end) as RagSociale, CAST(statoRic.DataAss AS DATE) + ISNULL(CONVERT(datetime, CONVERT(varchar(10), statoRic.OraDalle / 100)+ ':' + CONVERT(varchar(10), statoRic.OraDalle % 100)),'00:00') as eventstart, CAST(statoRic.DataAss AS DATE) + ISNULL(CONVERT(datetime, CONVERT(varchar(10), statoRic.OraAlle / 100)+ ':' + CONVERT(varchar(10), statoRic.OraAlle % 100)),'00:30') as eventend, Utenti.Nome as tecnico, statoRic.DataAss as data
From StatoRic
INNER Join
(Richieste INNER JOIN Clienti
On clienti.IDCliente=Richieste.RFCliente)
On StatoRic.RFRic=Richieste.IDRic
join Utenti
On utenti.IDUtente=StatoRic.RFTecnico
WHERE(RFStato = 11 or RFStato = 12 Or rfstato = 13 Or rfstato = 41) And Attuale=1 and StatoRic.DataAss is not null And RFTecnico=#tecnico and statoric.DataAss = #data
order by statoRic.DataAss asc"
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(query, con)
cmd.Parameters.AddWithValue("#data", data)
cmd.Parameters.AddWithValue("#tecnico", tecnico)
Using sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
childRepeater.DataSource = dt
childRepeater.DataBind()
End Using
End Using
End Using
End If
End Sub
Sub caricaTecnici()
Dim Query As String = "SELECT nome,idutente FROM Utenti WHERE attivo=1"
Dim cmd As New SqlCommand(query)
ddlTecnicoCal.DataSource = GetData(cmd)
ddlTecnicoCal.DataTextField = "nome"
ddlTecnicoCal.DataValueField = "idutente"
ddlTecnicoCal.DataBind()
ddlTecnicoCal.SelectedIndex = ddlTecnicoCal.Items.IndexOf(ddlTecnicoCal.Items.FindByValue(Session("idUtente")))
End Sub
Private Function GetData(cmd As SqlCommand) As DataTable
Dim strConnString As String = ConfigurationManager.ConnectionStrings("dbVulcanoConnectionString").ConnectionString
Using con As New SqlConnection(strConnString)
Using sda As New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Function
Protected Sub lnkPrevWeek_Click(sender As Object, e As EventArgs)
data1 = Date.ParseExact(hdnDa.Value, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
data2 = Date.ParseExact(hdnA.Value, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
Dim monday = data1.AddDays(-7)
Dim sunday = data2.AddDays(-7)
hdnDa.Value = monday
hdnA.Value = sunday
litData.Text = monday & " " & sunday
BindRepeater()
End Sub
Protected Sub lnkNextWeek_Click(sender As Object, e As EventArgs)
data1 = Date.ParseExact(hdnDa.Value, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
data2 = Date.ParseExact(hdnA.Value, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
Dim monday = data1.AddDays(7)
Dim sunday = data2.AddDays(7)
hdnDa.Value = monday
hdnA.Value = sunday
litData.Text = monday & " " & sunday
BindRepeater()
End Sub
End Class
Thanks!
I think your problem could be your global variables not preserving their new value after postback:
Dim data1, data2 As DateTime
Dim tecnico As Integer
Dim utente As Utenti
Try to store the values inside Session variables or Viewstate instead.
For example:
Session("tecnico") = x
ViewState("utente") = y
I've had this issue in the past.
The global variable doesn't keep its value
When I click on the vote button the detail will insert but all the the page detail insert I want only perticular button click data should insert.
Code:
Protected Sub vote(sender As Object, e As EventArgs) {
//( lblName,lbl_id ,lbl_name,Label1 this is all reapeater field id )
Dim lblName As Label
Dim lbl_id As Label
Dim lbl_name As Label
Dim Label1 As Label
For Each item As RepeaterItem In rpt_path.Items
lblName = CType(item.FindControl("lblName"), Label)
lbl_id = CType(item.FindControl("lbl_id"), Label)
lbl_name = CType(item.FindControl("lbl_name"), Label)
Label1 = CType(item.FindControl("Label1"), Label)
con=("Connection String")
con.Open()
Dim command As New OleDbCommand("insert into CFC(C_E_No,Name,Class_id,Party_id)values(#C_E_No,#Name,#Class_id,#Party_id)", con)
command.Parameters.AddWithValue("(#C_E_No", CType(item.FindControl("lblName"), Label).Text)
command.Parameters.AddWithValue("#Name", CType(item.FindControl("lbl_id"), Label).Text)
command.Parameters.AddWithValue("#Class_id", CType(item.FindControl("lbl_name"), Label).Text)
command.Parameters.AddWithValue("#Party_id", CType(item.FindControl("Label1"), Label).Text)
command.ExecuteNonQuery()
con.Close()
Design
<asp:Label ID="lbl_iid" runat="server" Text="Label" Visible="false"></asp:Label>
</div>
<asp:Label ID="lbl_iname" runat="server" Text="Label" Visible="false"></asp:Label>
<asp:Label ID="lbl_icid" runat="server" Text="Label" Visible="false"></asp:Label>
<asp:Label ID="lbl_ipid" runat="server" Text="Label" Visible="false"></asp:Label>
Coding on Vote Button Click
Protected Sub vote(sender As Object, e As EventArgs)
Dim str As String = CType(sender, Button).CommandArgument
Session("vid") = str
MsgBox(Session("vid"))
Connection String
cmd = New OleDbCommand("select * from candi where C_E_No='" & str.ToString() & "' ")
ds = New DataSet
cmd.Connection = con
con.Open()
da = New OleDbDataAdapter(cmd)
MsgBox(cmd.CommandText)
da.Fill(ds, "candi")
lbl_iid.Text = ds.Tables(0).Rows(0)(0)
lbl_iname.Text = ds.Tables(0).Rows(0).Item(1).ToString()
lbl_icid.Text = ds.Tables(0).Rows(0).Item(2).ToString()
lbl_ipid.Text = ds.Tables(0).Rows(0).Item(4).ToString()
con.Close()
Connection String
cmd = New OleDbCommand("insert into CFC(Stu_E_No,C_E_No,Name,Class_id,Party_id)values('" & Session("stdid") & "','" & lbl_iid.Text & "','" & lbl_iname.Text & "','" & lbl_icid.Text & "','" & lbl_ipid.Text & "') ")
MsgBox(cmd.CommandText)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Succes")
I have 2 Linkbuttons inside each row of my gridview.
I want to know how I can use If statements to determine which changes should be made.
My current If statements(which I know are wrong) are as follows:
If LinkButton1.Text = "Update" Then
Dim row As GridViewRow = DisplayClassifieds.SelectedRow
strFilter = row.Cells(1).Text
strSelect = "SELECT Classid, Addate, Category, Username, Phonenbr, Email, Description, Fulldescription FROM TABLENAME WHERE Classid = '" & strFilter & "' "
Page.Session.Add("Admin_Updates", strSelect)
Response.Redirect("DispAd.aspx")
ElseIf LinkButton2.Text = "Delete" Then
Dim ClassifiedStr As New OleDbCommand
ClassifiedStr.CommandType = CommandType.StoredProcedure
ClassifiedStr.CommandText = "delete_classifieds"
ClassifiedStr.Connection = conn
'Must be organized based on Stored Procedure
ClassifiedStr.Parameters.Add("val_id", OleDbType.Date).Value = strFilter
conn.Open()
ClassifiedStr.ExecuteNonQuery()
conn.Close()
Response.AddHeader("Refresh", "1")
End if
What do I use in place of my lines If LinkButton1.Text = "Update"
Update:
I added CommandName="UpdateRow" and "DeleteRow" to HTML Linkbutton and did the following:
If LinkButton1.CommandName = "UpdateRow"
and
ElseIf LinkButton2.CommandName = "DeleteRow" Then
However, the Delete one simply Deletes the LinkButton and not the Database record which is weird?! Not sure why.
I also see that the Display button will only work once I click Delete, change page, go back to first page which has Delete Removed. So if Delete is present Display doesn't work.
UPDATED FULL VERSION THAT DOESN'T WORK
VERSION 1
Protected Sub DisplayClassifieds_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DisplayClassifieds.SelectedIndexChanged
Dim conn As OleDbConnection = New OleDbConnection("Provider=""********"";user id=" & strUserID & ";data source=" & strDatabase & ";password=" & strPssWd)
Dim strSelect As String
Dim strFilter As String = " "
' Dim counter As Integer = 0
' Dim v As Integer = 0
'cell = DisplayClassifieds[0,Row].Value
Dim row As GridViewRow = DisplayClassifieds.SelectedRow
strFilter = row.Cells(1).Text
strSelect = "SELECT Classid, Addate, Category, Username, Phonenbr, Email, Description, Fulldescription FROM TABLENAME WHERE Classid = '" & strFilter & "' "
If LinkButton1.commandName = "UpdateRow" Then
Page.Session.Add("Admin_Updates", strSelect)
Response.Redirect("DispAd.aspx")
ElseIf LinkButton2.commandName = "DeleteRow" Then
Dim ClassifiedStr As New OleDbCommand
ClassifiedStr.CommandText = "DELETE * FROM TABLENAME WHERE Classid = '" & strFilter & "'"
ClassifiedStr.Connection = conn
'Must be organized based on Stored Procedure
ClassifiedStr.Parameters.Add("val_id", OleDbType.Date).Value = strFilter
conn.Open()
ClassifiedStr.ExecuteNonQuery()
conn.Close()
Response.AddHeader("Refresh", "1")
Response.Redirect("QRY2.aspx")
End If
End Sub
VERSION 2
Sub LinkButton1_Click(sender As Object, e As EventArgs)
Dim conn As OleDbConnection = New OleDbConnection("Provider=""********"";user id=" & strUserID & ";data source=" & strDatabase & ";password=" & strPssWd)
Dim strSelect As String
Dim strFilter As String = " "
Dim counter As Integer = 0
Dim v As Integer = 0
'cell = DisplayClassifieds[0,Row].Value
Dim row As GridViewRow = DisplayClassifieds.SelectedRow
strFilter = row.Cells(1).Text
strSelect = "SELECT Classid, Addate, Category, Username, Phonenbr, Email, Description, Fulldescription FROM TABLENAME WHERE Classid = '" & strFilter & "' "
Page.Session.Add("Update_Values", strSelect)
Response.Redirect("DispAdUpdate.aspx")
End Sub
Sub LinkButton2_Click(sender As Object, e As EventArgs)
Dim conn As OleDbConnection = New OleDbConnection("Provider=""*******"";user id=" & strUserID & ";data source=" & strDatabase & ";password=" & strPssWd)
Dim strFilter As String = " "
Dim row As GridViewRow = DisplayClassifieds.SelectedRow
strFilter = row.Cells(1).Text
Dim ClassifiedStr As New OleDbCommand
ClassifiedStr.CommandType = CommandType.StoredProcedure
ClassifiedStr.CommandText = "delete_classifieds"
ClassifiedStr.Connection = conn
'Must be organized based on Stored Procedure
ClassifiedStr.Parameters.Add("val_id", OleDbType.Date).Value = strFilter
conn.Open()
ClassifiedStr.ExecuteNonQuery()
conn.Close()
Response.AddHeader("Refresh", "1")
Response.Redirect("QRY2.aspx")
End Sub
You should put strFilter = row.Cells(1).Text line above if statement (If LinkButton1.Text = "Update" Then).
It looks like doing this process is very hard.
I decided to do a "select" option instead since my question seemed difficult.
I do this like so:
For the select option row:
Protected Sub DisplayClassifieds_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DisplayClassifieds.SelectedIndexChanged
Dim row As GridViewRow = DisplayClassifieds.SelectedRow
End Sub
Then making a delete and update button that takes that index as so....
Protected Sub BtnDelete_Click(sender As Object, e As EventArgs) Handles BtnDelete.Click
Dim conn As OleDbConnection = New OleDbConnection("Provider=""******"";user id=" & strUserID & ";data source=" & strDatabase & ";password=" & strPssWd)
If Page.IsValid Then
If DisplayClassifieds.SelectedIndex = -1 Then
Response.Write("<script language=""javascript"">alert('You must select a record.');</script>")
Exit Sub
End If
Dim ClassifiedStr As New OleDbCommand
ClassifiedStr.CommandType = CommandType.StoredProcedure
ClassifiedStr.CommandText = "delete_classifieds"
ClassifiedStr.Connection = conn
'Must be organized based on Stored Procedure
'DataKey is the DataKey that we labeled as Classid(same name as ID field in Oracle)
ClassifiedStr.Parameters.Add("val_id", OleDbType.Numeric).Value = CInt(DisplayClassifieds.SelectedDataKey.Value)
conn.Open()
ClassifiedStr.ExecuteNonQuery()
....etc
The bottom "DataKey" code from my VB.net comes from the table options I made with the use of "DataKeyNames" value :
<asp:GridView ID="DisplayClassifieds" runat="server" align="center"
Width="100%" AllowSorting="True" AutoGenerateColumns="False"
AutoGenerateSelectButton="True" EnableModelValidation="True"
BorderColor="Black" BorderStyle="Solid" DataKeyNames="Classid" >
<Columns>
<asp:BoundField DataField="Classid" HeaderText="ID"
SortExpression="Date" Visible = "false">
<ItemStyle cssClass="grid_padding" />
</asp:BoundField>
....etc
</Columns>
</asp:GridView>
I'm not as familiar with using/calling stored procedures but, if it's not too much of a hassle, try typing your delete query out in the commandtext property, ex.
ElseIf LinkButton2.Text = "Delete" Then
Dim ClassifiedStr As New OleDbCommand
ClassifiedStr.CommandText = "DELETE * FROM TABLENAME WHERE val_id = #val_id"
ClassifiedStr.Connection = conn
'Must be organized based on Stored Procedure
ClassifiedStr.Parameters.AddWithValue("#val_id", strFilter)
conn.Open()
ClassifiedStr.ExecuteNonQuery()
conn.Close()
Response.AddHeader("Refresh", "1")
End if
Since I haven't ever called stored procedures I am just guessing that it has something to do with the way you are calling it for delete
I'm not getting my GridViewUpdateEventArgs to work for some reason.
I'm trying to update my gridview(table in sql) but it´s not working.
And i don´t know how to write the the Where clause in the sql to match.
Public Sub GridView1_RowUpdating(sender As Object, e As GridViewUpdateEventArgs)
Dim SelectRow As GridViewRow = Gridview1.Rows(e.RowIndex)
Dim RowID As HiddenField = Gridview1.FindControl("ID")
Dim Report As String = SelectRow.Cells(1).Text
Dim BusinessArea As String = SelectRow.Cells(2).Text
Dim Salesdepartment As String = SelectRow.Cells(3).Text
Using SqlConnection As New SqlConnection(SqlConnectionString)
SqlConnection.Open()
Dim SqlCommand As New SqlCommand("UPDATE TEST SET Report = ('" & Report & "'), [Business Area] = ('" & BusinessArea & "'), Salesdepartment = ('" & Salesdepartment & "') WHERE ID = #RowID ", SqlConnection)
Dim SqlDataAdapter As New SqlDataAdapter(SqlCommand)
Dim dataSet As New DataSet()
SqlDataAdapter.Fill(dataSet)
Gridview1.EditIndex = -1
BindDataToGridView()
SqlConnection.Close()
End Using
The "ID" column is my PK in the table and is in a (ItemTemplate) (Hidden)
In this Way SqlDataAdapter can't update database record, see here how to update record using SqlDataAdapter .
or you can try like this:
Dim row As GridViewRow = Gridview1.Rows(e.RowIndex)
Dim hf As HiddenField = TryCast(row.FindControl("ID"), HiddenField)
Dim Report As [String] = row.Cell(1).Text
Dim BusinessArea As [String] = row.Cell(2).Text
Dim Salesdepartment As [String] = row.Cell(3).Text
Using SqlConnection As New SqlConnection(SqlConnectionString)
SqlConnection.Open()
Dim cmd As New SqlCommand("UPDATE TEST SET Report = #Report,[Business Area] =#BusinessArea, Salesdepartment=#Salesdepartment WHERE ID = #RowID ", SqlConnection)
cmd.Parameters.AddWithValue("#Report", Report)
cmd.Parameters.AddWithValue("#BusinessArea", BusinessArea)
cmd.Parameters.AddWithValue("#Salesdepartment", Salesdepartment)
cmd.Parameters.AddWithValue("#RowID", hf.Value)
cmd.ExecuteNonQuery()
Gridview1.EditIndex = -1
BindDataToGridView()
SqlConnection.Close()
End Using
I have a survey page, where i insert radio buttons dinamically in form load event. When i click the button to send the results, after postback, the radio buttons are still there, with the checked state correctly. But if i do some code, in the code behind, that tries to check if one of them is checked (by FindControl(id)), the page crashes. I can´t do debug, so i don't know what error is.
<%# Control language="vb" AutoEventWireup="false" Explicit="True" Inherits="DotNetNuke.UI.Skins.Skin" %>
<%# Register TagPrefix="dnn" TagName="USER" Src="~/Admin/Skins/User.ascx" %>
<style>
body {background-image:none; background-color:transparent;}
</style>
<div style="float:left; width:420px; height:335px;" id="divPerguntas" enableviewstate="true" runat="server"></div>
<div style="float:left; width:420px; height:75px;"><asp:ImageButton ImageUrl="/Portals/_default/Skins/AdWin/img/Enviar.png" id="imgEnviar" runat="server" style="cursor:pointer;" /></div>
<div id="ContentPane" runat="server"></div>
<script runat="server">
Protected Sub EnviarClick() Handles imgEnviar.Click
Dim conexao As SqlConnection
Dim comando As SqlCommand
Dim myReader As SqlDataReader
Dim sql As String
sql = "SELECT S.SurveyID, SO.SurveyOptionID FROM AdWin_Demo.dbo.Surveys S INNER JOIN AdWin_Demo.dbo.SurveyOptions SO ON S.SurveyID = SO.SurveyID WHERE S.VideoId = " + Request.QueryString("id") + " ORDER BY S.ViewOrder, SO.ViewOrder"
conexao = New SqlConnection("#CONNECTIONSTRING#")
conexao.Open()
comando = New SqlCommand(sql, conexao)
myReader = comando.ExecuteReader
If myReader.HasRows Then
Dim dt As New DataTable
dt.Load(myReader)
Dim SurveyID As Integer = 0
Dim FirstQuestion As Boolean = True
Dim checkedGroup As Boolean = False
Dim insertList As New DataTable
Dim ColumnIDSurveyOption As New DataColumn("c", GetType(Integer))
insertList.Columns.Add(ColumnIDSurveyOption)
Dim row As DataRow
For Each dr As DataRow In dt.Rows
If FirstQuestion Then
SurveyID = dr("SurveyID")
FirstQuestion = False
End If
If SurveyID <> dr("SurveyID") Then
SurveyID = dr("SurveyID")
checkedGroup = False
End If
If SurveyID = dr("SurveyID") And checkedGroup = False Then
Dim radiobuttonToCheck As RadioButton = FindControl(dr("SurveyOptionID").ToString())
If radiobuttonToCheck.Checked Then
checkedGroup = True
row = insertList.NewRow()
row("insertList") = dr("SurveyOptionID")
insertList.Rows.Add(row)
End If
End If
Next
If checkedGroup = True Then
Dim dnnUserCtrl As New DotNetNuke.Entities.Users.UserController
For Each dr As DataRow In insertList.Rows
sql = "INSERT INTO AdWin_Demo.dbo.Adwin_RespostasDadas (IDUser, SurveyOptionID) SELECT " & dnnUserCtrl.GetCurrentUserInfo.UserID & ", " & dr("SurveyOptionID").ToString()
comando = New SqlCommand(sql, conexao)
myReader = comando.ExecuteReader
Next
Else
Response.Write("Nao respondeste a tudo")
End If
End If
myReader.Close()
conexao.Close()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Me.EnableViewState = True
'If Not Page.IsPostBack Then
Dim conexao As SqlConnection
Dim comando As SqlCommand
Dim myReader As SqlDataReader
Dim sql As String
sql = "SELECT S.SurveyID, S.Question, SO.OptionName, SO.SurveyOptionID FROM AdWin_Demo.dbo.Surveys S INNER JOIN AdWin_Demo.dbo.SurveyOptions SO ON S.SurveyID = SO.SurveyID WHERE S.VideoId = " + Request.QueryString("id") + " ORDER BY S.ViewOrder, S.SurveyID, SO.ViewOrder"
conexao = New SqlConnection("#CONNECTIONSTRING#")
conexao.Open()
comando = New SqlCommand(sql, conexao)
myReader = comando.ExecuteReader
If myReader.HasRows Then
Dim dt As New DataTable
dt.Load(myReader)
Dim SurveyID As Integer = 0
Dim FirstQuestion As Boolean = True
Dim ActualDiv As System.Web.UI.HtmlControls.HtmlGenericControl
For Each dr As DataRow In dt.Rows
If SurveyID = dr("SurveyID") Then
Dim rb As New RadioButton
rb.GroupName = "Group" & SurveyID.ToString()
rb.ID = dr("SurveyOptionID").ToString()
rb.Text = dr("OptionName").ToString()
rb.EnableViewState = True
ActualDiv.Controls.Add(rb)
ActualDiv.Controls.Add(New LiteralControl("<br/>"))
Else
SurveyID = dr("SurveyID")
If FirstQuestion = False Then
Dim hr2 As New HtmlGenericControl("hr")
divPerguntas.Controls.Add(hr2)
End If
Dim div As New System.Web.UI.HtmlControls.HtmlGenericControl("DIV")
div.Style.Add("float", "left")
div.Style.Add("width", "400px")
div.Style.Add("color", "#777")
div.Style.Add("font-size", "11px")
div.Style.Add("line-height", "15px")
divPerguntas.Controls.Add(div)
ActualDiv = div
ActualDiv.InnerText = dr("Question").ToString()
ActualDiv.Controls.Add(New LiteralControl("<br/>"))
Dim rb As New RadioButton
rb.GroupName = "Group" & SurveyID.ToString()
rb.ID = dr("SurveyOptionID").ToString()
rb.Text = dr("OptionName").ToString()
rb.EnableViewState = True
ActualDiv.Controls.Add(rb)
ActualDiv.Controls.Add(New LiteralControl("<br/>"))
FirstQuestion = False
End If
Next
Dim hr As New HtmlGenericControl("hr")
divPerguntas.Controls.Add(hr)
End If
myReader.Close()
conexao.Close()
End Sub
</script>
Try to add controls to the page in PreInit event and see if you can access data correctly. More details here http://msdn.microsoft.com/en-us/library/ms178472.aspx
Dim radiobuttonToCheck As RadioButton = FindControl(dr("SurveyOptionID").ToString())
->
Dim radiobuttonToCheck As RadioButton = Me.FindControl(dr("SurveyOptionID").ToString())