Add conditional dropdownlist items in ASPX Application (VB) - asp.net

I have a GridView with a asp:dropdownlist
I am able to add dropdown values using rowdatabound.
However what I need to do, is add specific dropdown list values base on the contents of another cell in that row.
So for example if Row(1) and Cell(2) = MAR001, I want the Dropdown values Four, Five and Six
However if Row(1) and Cell(2) <> MAR001, I want the dropdown values One, Two and Three.
Here is my attempt using a loop, however it doesn't target the dropdown values correctly.
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
For i As Integer = 0 To GridView1.Rows.Count - 1
Dim Name As String = GridView1.Rows(i).Cells(2).Text
If Name = "MAR001" Then
Dim ddl As DropDownList = e.Row.FindControl("ddlQuantity")
Dim numbers As New List(Of String)()
numbers.Add("Four")
numbers.Add("Five ")
numbers.Add("Six")
ddl.DataSource = numbers
ddl.DataBind()
Else
Dim ddl As DropDownList = e.Row.FindControl("ddlQuantity")
Dim numbers As New List(Of String)()
numbers.Add("One")
numbers.Add("Two")
numbers.Add("Three")
ddl.DataSource = numbers
ddl.DataBind()
End If
Next
Else
End If
End Sub
Any help much appreciated.

Not sure if this is what you need, but try finding the textbox first and get the text value of that.
Edit: i just realized you're looping the rows. you don't have to do that - this is the RowDataBound event, so this code happens for every row.
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ddl As DropDownList = e.Row.FindControl("ddlQuantity")
Dim numbers As New List(Of String)()
Dim customerid As String = (e.Row.Cells(2).Text)
If customerid = "MAR001" Then
numbers.Add("Four")
numbers.Add("Five ")
numbers.Add("Six")
Else
numbers.Add("One")
numbers.Add("Two")
numbers.Add("Three")
End If
ddl.DataSource = numbers
ddl.DataBind()
End If

Related

Deleting multiple Rows in GridView using Checkbox, Delete button outside of the Grid, without going to database

How do I delete multiple Rows in a GridView using a Checkbox, Delete button outside of the Grid, without going to database?
My purpose is to be able to delete multiple rows by SelectedCheckbox in the Gridview. After that, I use data show in gridview to make changes in database.
Dim dt As DataTable = ViewState("gridview")
Dim row As GridViewRow
For Each row In gridview.Rows
Dim SelectedRow As CheckBox = CType(row.FindControl("cbSelect"), CheckBox)
If SelectedRow.Checked Then
'gridview.rows(row.index).visible = false is not my case because those indexes are still there
End If
Next
I couldn't usegridview.rows(row.index).remove()/delete()
My 2nd option is store gridview to datatable by viewstate(). When i try to remove index in the FOR EACH loop, it showed error because after the 1st remove the datatable reindex.
Thanks for your help.
I got my 2nd option done by deleting row from bottom up.
I really appreciate If anyone could help me with my 1st option.
Dim dt As DataTable = ViewState("gridview")
For i As Integer = gridview.Rows.Count - 1 To 0 Step -1
Dim row As GridViewRow = gridview.Rows(i)
Dim SelectedRow As CheckBox = CType(row.FindControl("cbSelect"), CheckBox)
If SelectedRow.Checked Then
dt.Rows(i).Delete()
End If
Next
gridview.DataSource = dt
gridview.DataBind()
Yes, yes, delete each row from the bottom up. I believe it will be like this.
Private Sub Button_Delete_Checked_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button_Delete_Checked.Click
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells("ToDelete").Value Then
MessageBox.Show(row.Cells("SomeText").Value & " will be deleted.")
End If
Next
End Sub
As for the Insert Into, this methodology should work fine.
Dim Con As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Music_Sales_Database.mdb;")
Dim Com As OleDbCommand
Dim SaleCode As Integer
Dim MusicID As String
Dim SubTotalPrice As Decimal
Dim Copies1 As Integer
Dim STR1 As String
SaleCode = 1
Com = New OleDbCommand
Com.Connection = Con
Connection.open()
For x As Integer = 0 To SalesDataGridView.Rows.Count - 1
MusicID = SalesDataGridView.Rows(x).Cells(0).Value
SubTotalPrice = SalesDataGridView.Rows(x).Cells(5).Value
Copies1 = SalesDataGridView.Rows(x).Cells(3).Value
STR1 = "INSERT INTO Sales(Sales_ID, Sales_Date, Copies, Music_ID, Staff_ID, Total_Price) VALUES (#Sales_ID, #Sales_Date, #Copies, #Music_ID, #Staff_ID, #Total_Price)"
Dim Comm As New OleDbCommand(STR1, Con)
Comm.Parameters.AddWithValue("#Sales_ID", SaleCode)
Comm.Parameters.AddWithValue("#Sales_Date", txtDateAndTime)
Comm.Parameters.AddWithValue("#Copies", Copies1)
Comm.Parameters.AddWithValue("#Music_ID", MusicID)
Comm.Parameters.AddWithValue("#Staff_ID", txtStaff_ID)
Comm.Parameters.AddWithValue("#Total_Price", SubTotalPrice)
Command.ExecuteNonQuery()
Comm.Dispose()
Next
Connection.Close()
Obviously, you need to modify this to suit your specific needs.

asp.net looping through dynamic control in a table

i have a table which contains questions and a bunch of dynamically created radio button lists, i m trying to write code which will loop through each one of the radio button list and get the value of the selected question value and corresponding question id . i have the following code which returns the selected radio button list value.how i will get questions ids as well as their selected value?
For Each ctrl As Control In form1.Controls
If TypeOf ctrl Is RadioButtonList Then
Dim rbl As RadioButtonList = DirectCast(ctrl, RadioButtonList)
For i As Integer = 0 To rbl.Items.Count - 1
If rbl.Items(i).Selected Then
Dim value As String = rbl.SelectedValue
End If
Next
End If
Next
When creating the radio buttons you should put them into a dictionary (make sure to do so in the Init phase). The String key is assumed to hold the question id:
Dim radios As New Dictionary(Of String, RadioButtonList)
Dim table As DataTable
Sub Page_Init(sender As Object, e As EventArgs)
table = ...
For Each row As DataRow In table.Rows
Dim rbl As New RadioButtonList
' add radio buttons to rbl
radios.Add(row("id").ToString, rbl)
Next
End Sub
Then in the event handler for retrieving the answers you can easily access them:
Sub MyHandler(sender As Object, e As EventArgs)
For Each row As DataRow In table.Rows
Dim value As String = GetAnswer(row("id").ToString)
' do something with the answer ...
Next
End Sub
Function GetAnswer(id As String) As String
For Each item In radios(id)
If item.Selected Then Return item.SelectedValue
Next
Return Nothing
End Function

How to delete row from gridview's RowDataBound event

I am trying to delete a row from a gridview (based on a condition) and then add than row to another gridview inside of the "master" gridview's RowDataBound event. Originally I did not know that in order to call .DeleteRow(i) you needed to have an "ondelete" event handler. However, since all the gridview's .DeleteRow method does is call this event handler, I am confused as to how to use it. Can someone please help point me in the right direction?
Protected Sub grdProduct_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdProduct.RowDataBound
' Grey out expired products
Dim row As GridViewRow
row = e.Row
Dim incomingDate As String
Dim incomingStatus As String = ""
incomingDate = row.Cells(3).Text.ToString()
incomingStatus = row.Cells(5).Text.ToString()
If (e.Row.RowType <> DataControlRowType.DataRow) Then
Exit Sub
End If
Try
Dim expDate As Date = incomingDate
If (expDate < DateTime.Today Or incomingStatus.Equals("D")) Then
'Create object for RowValues
Dim RowValues As Object() = {"", "", "", "", "", ""}
'Create counter to prevent out of bounds exception
Dim i As Integer = row.Cells.Count
'Fill row values appropriately
For index As Integer = 0 To i - 1
RowValues(index) = row.Cells(index).Text
Next
'create new data row
dProdRow = dProdtable.Rows.Add(RowValues)
dProdtable.AcceptChanges()
grdProduct.DeleteRow(e.Row.RowIndex)
End If
Catch ex As Exception
End Try
End Sub
Protected Sub grdProduct_Delete(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles grdProduct.RowDeleting
'Not sure what to do here
End Sub
The best way to do this is to manipulate this at the datasource level rather than manipulating the UI components themselves.
For example:
if(!IsPostback)
{
DataTable one = ...
DataTable two = ...
var removeRows = (from c in one.AsEnumerable()
where c.Field<DateTime>("incomingDate")< incomingDate ||
c.Field<string>("incomingStatus")=="D"
select c).ToList();
for(var item in removeRows)
{
two.ImportRow(item);
}
//now delete from initial table
foreach(var item in removeRows)
{
one.Rows.Remove(item);
}
//Now bind both grids
grid1.DataSource=one;
grid1.DataBind();
grid2.DataSource=two;
grid2.DataBind();
}
Update - Sample toy program in VB.NET Hopefully you can adapt it to your situation.
Sub Main
Dim one As New DataTable()
one.Columns.Add("one", GetType(Integer))
For i As Integer = 0 To 9
Dim r As DataRow = one.NewRow()
r.ItemArray = New Object() {i}
one.Rows.Add(r)
Next
Dim two As New DataTable()
two.Columns.Add("one", GetType(Integer))
For i As Integer = 0 To 9
Dim r As DataRow = two.NewRow()
r.ItemArray = New Object() {i}
two.Rows.Add(r)
Next
Dim removeRows = (From c In one.AsEnumerable() Where c.Field(Of Integer)("one") = 5).ToList()
For Each item As DataRow In removeRows
two.ImportRow(item)
Next
For Each item As DataRow In removeRows
one.Rows.Remove(item)
Next
End Sub
I just realized that you are using VB.NET. You should be able to translate the above from C# to VB.NET. The general idea is there, anyway.

Gridview Header with sort-icon

I am binding a data set to a GridView in VB .net. I have some custom sorting setup, and want to display an icon next to the header if one of my 3 options is selected.
I've read a lot of methods in doing this, and I see Gridviews even have a ASC and DESC header style I can associate with the view. I have 2 problems with this, though:
I am sorting a List with linq on Sort Trigger, then binding it to the datagrid.
The reason I do it this way, is I want to maintain multiple sort levels, ordering by 3 columns rather than 1.
Edit for clarity
Specifically what I want to do is loop through the value of a GridView's Header text, see if it matches what I have saved in viewstate, and if so add an image for that header in particular. Something essentially like below, however headerRow.Cells(y).Text is always returning "", even when the header has text:
Sub gvPatronData_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim savedSortDirection(), savedSortColumn() As String
Dim headerRow As GridViewRow = gvPatronData.HeaderRow
'this sets the values of these variables
'as strings equal to the text displayed in the header of the gridview
_patronBl.SplitPatronSort(savedSortDirection, SortDirection, savedSortColumn, SortColumn)
If SortDirection <> "" Then
If e.Row.RowType = DataControlRowType.Header Then
For x = 0 To savedSortDirection.Length - 1
For y = 0 To headerRow.Cells.Count - 1
If headerRow.Cells(y).Text = savedSortColumn(x) Then
If savedSortDirection(x) = "Ascending" Then
Dim bGStyle As New System.Web.UI.WebControls.Style()
bGStyle.CssClass = "upSort"
headerRow.Cells(y).ApplyStyle(bGStyle)
Else
Dim bGStyle As New System.Web.UI.WebControls.Style()
bGStyle.CssClass = "downSort"
headerRow.Cells(y).ApplyStyle(bGStyle)
End If
End If
Next
Next
End If
End If
End Sub
Have you tried to loop the GridView's Columns instead of the the GridViewRow's Cell-Collection? A DataControlField has a HeaderText property.
For Each col As DataControlField In gvPatronData.Columns
If col.HeaderText = savedSortColumn(x) Then
If savedSortDirection(x) = "Ascending" Then
Dim bGStyle As New System.Web.UI.WebControls.Style()
bGStyle.CssClass = "upSort"
headerRow.Cells(gvPatronData.Columns.IndexOf(col)).ApplyStyle(bGStyle)
Else
Dim bGStyle As New System.Web.UI.WebControls.Style()
bGStyle.CssClass = "downSort"
headerRow.Cells(gvPatronData.Columns.IndexOf(col)).ApplyStyle(bGStyle)
End If
End If
Next
This is how I ended up doing it. Actually drilling into the table objects was where I was coming up short before.
Sub gvPatronData_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim savedSortDirection(), savedSortColumn() As String
Dim columnCollection As DataControlFieldCollection = gvPatronData.Columns
_patronBl.SplitPatronSort(savedSortDirection, SortDirection, savedSortColumn, SortColumn)
If e.Row.RowType = DataControlRowType.Header Then
For x = 0 To savedSortDirection.Length - 1
For Each col As DataControlField In columnCollection
If col.HeaderText = _headerDictionary(savedSortColumn(x)) Then
If savedSortDirection(x) = "Ascending" Then
e.Row.Cells(gvPatronData.Columns.IndexOf(col)).Attributes.Add("Style", _
"background-image: url(images/arrow_up.png);background-repeat:no-repeat;background-position: 96% 50%;")
Else
e.Row.Cells(gvPatronData.Columns.IndexOf(col)).Attributes.Add("Style", _
"background-image: url(images/arrow_down.png);background-repeat:no-repeat;background-position: 96% 50%;")
End If
End If
Next
Next
End If
_headerDictionary : This was a dictionary of my DataField to HeaderText strings, since my savedSortColumn was the data field to sort on.
Def:
Public Function ColumnDataFieldToHeaderTextDictionary() As Dictionary(Of String, String)
Dim dict As New Dictionary(Of String, String)
dict.Add("FirstName", "First Name")
dict.Add("LastName", "Last Name")
dict.Add("Phone", "Phone Number")
dict.Add("Phone2", "Alternate Phone Number")
dict.Add("Email", "Email")
Return dict
End Function

use gridview row control in sqldatasource insert command

I am trying to use a label from another row in the gridview and insert it in a table when the user clicks the button which is in its own column.
my problem is that i cant get bookno which finds the label set to the #bookno in my sqldatasource
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim selectedRow As Button = DirectCast(sender, Button)
Dim bookno As Label = CType(selectedRow.FindControl("label1"), Label)
Dim why As TextBox = CType(selectedRow.FindControl("textbox2"), TextBox)
Dim yesint As Integer = 1
Dim sql As SqlDataSource = CType(selectedRow.FindControl("sqldatasource4"), SqlDataSource)
sql.InsertParameters.Add(bookno.Text, 0)
sql.Insert()
End Sub
Try
Dim bookno As Label = CType(selectedRow.Parent.FindControl("label1"), Label)
and see if you get a valid control for bookno. If it works, do the same for other FindControl() calls.

Resources