I have a object in previous code and it is bind on datagrid. Now I need to add sort the column. I search the web to convert the dataTable from datasource. But I got an error'DataTable must be set prior to using DataView.'
Does anyone tell me how to do it? Thanks in advance.
there is the code to bind the datagrid:
Dim thisOrder as New co.Orders(123)
dgrdOrders.DataSource=thisOrder
dgrdOrders.DataBind()
there is my code:
Private Sub dgrdOrders_SortCommand(source As Object, e As DataGridSortCommandEventArgs) Handles dgrdOrders.SortCommand
Dim dataTable As DataTable = TryCast(dgrdOrders.DataSource, DataTable)
Dim dv As New DataView(dataTable)
dv.Sort = e.SortExpression
dgrdOrders.DataSource = dv
dgrdOrders.DataBind()
End Sub
Finally I found the way to sort it:
Private Sub dgrdOrders_SortCommand(source As Object, e As DataGridSortCommandEventArgs) Handles dgrdOrders.SortCommand
Dim lstOrders As New List(Of co.Order)
For Each objOrder As co.Order In thisOrder
lstOrders.Add(objOrder)
Next
Select Case e.SortExpression
Case "Type"
lstOrders = lstOrders.OrderBy(Function(x) x.Type).ToList
Case "Region"
lstOrders = lstOrders.OrderBy(Function(x) x.Region).ToList
End Select
dgrdOrders.DataSource = lstOrders
dgrdOrders.DataBind()
End Sub
Related
I'm trying to do display multiple rows with two column values on a list box so when a user selects an option they have a little extra information.
It should look like this:
ej. 3 BestBuy
I use the same method to output data to my GridViews but it doesn't display anything on the listbox. What is the correct method to output data from a db to a listbox.
SQL Control Class Functions
Public Function ExecQuery(query As String) As DataTable
Dim DBDT = New DataTable
Using DBCon As New SqlConnection(ConStr),
DBCmd As New SqlCommand(query, DBCon)
Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))
Params.Clear()
DBCon.Open()
DBDT.Load(DBCmd.ExecuteReader)
End Using
Return DBDT
End Function
'Add Params
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New SqlParameter(Name, Value)
Params.Add(NewParam)
End Sub
How im trying to add data to the listbox
Protected Sub DivisionListBox_DataBinding(sender As Object, e As EventArgs) Handles DivisionListBox.DataBinding
Try
dt = SQL.ExecQuery("Select STR_GRP_ID, GROUP_DESC
FROM Store_Group_Desc ")
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
DivisionListBox.DataSource = dt
DivisionListBox.DataBind()
End Sub
What I would do is return the STR_GRP_ID as well as create an aliased column that concatenated the STR_GRP_ID and GROUP_DESC fields.
Then you would bind the DataTable to the ListBox like you're doing but specifying that the ListBox's DisplayMember is your aliased column and the ValueMember is the id:
Try
dt = SQL.ExecQuery("Select STR_GRP_ID, CONCAT_WS(' ', STR_GRP_ID, GROUP_DESC GROUP_DESC) AS DisplayText FROM Store_Group_Desc;")
Catch ex As Exception
MessageBox.Show(ex.Message)
Return
End Try
With DivisionListBox
.DataSource = dt
.DisplayMember = "DisplayText"
.ValueMember = "STR_GRP_ID"
End With
I don't think the DataBinding event will ever be triggered in you code. You can set a break point inside the event and see if it is ever triggered.
I chose to use the Page.Load event to fill the list box. I separated the user interface code that actually fills the list box from the data access code.
I had the server do the work to build the string your want to display. I assumed the id field was some type of number field so I cast it to a varchar. Then added a space and the description field. This new select field is called IDDesc.
IDDesc is the field name that I want to display in the list box.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
FillListBox()
End If
End Sub
Private Sub FillListBox()
Dim ListBoxData = GetListBoxData()
ListBox1.DataTextField = "IDDesc"
ListBox1.DataSource = ListBoxData
ListBox1.DataBind()
End Sub
Private Function GetListBoxData() As DataTable
Dim DBDT = New DataTable
Dim Query = "Select Cast(STR_GRP_ID As varchar) + ' ' + GROUP_DESC As IDDesc
FROM Store_Group_Desc "
Using DBCon As New SqlConnection(ConStr),
DBCmd As New SqlCommand(Query, DBCon)
DBCon.Open()
DBDT.Load(DBCmd.ExecuteReader)
End Using
Return DBDT
End Function
I am using ASP.NET with VB.NET and I want the user add several row to data table.
I am trying to add multi row into data table in run time by (textboxes, rad combo box and check box).
I add first row second and third row.
But when I present the data table its show only the last row I enter
so the table contain only one row.
How do I keep all row in data table not only one row? I tried everything please help.
This is my code:
Dim dcItemID = New DataColumn("ItemID", GetType(Int32))
Dim dcUnit = New DataColumn("UnitID", GetType(Int32))
Dim ItemPrice = New DataColumn("ItemPrice", GetType(Int32))
Dim sellprice = New DataColumn("SellPrice", GetType(Int32))
dt.Columns.Add(dcItemID)
dt.Columns.Add(dcUnit)
dt.Columns.Add(ItemPrice)
dt.Columns.Add(sellprice)
dt.Rows.Add(Convert.ToInt32(rcItemName.SelectedValue), Convert.ToInt32(rcUnitID.SelectedValue), tbItemPrice.Text, tbSellprice.Text)
thank u all i found the answer
if any one interested this is my solution :
Public Class WebForm1
Inherits System.Web.UI.Page
Private dt As DataTable = New DataTable()
Private dr As DataRow = Nothing
Protected Sub btnSaved_Click(sender As Object, e As EventArgs) Handles btnSaved.Click
If ViewState("table") IsNot Nothing Then
dt = CType(ViewState("table"), DataTable)
End If
dr = dt.NewRow()
dr("ItemPrice") = tbItemPrice.Text
dr("SellPrice") = tbSellprice.Text
' dr("Product_Amount") = txtAmount.Text
dt.Rows.Add(dr)
ViewState("table") = dt
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
dt.Columns.Add("ItemPrice")
dt.Columns.Add("SellPrice")
End Sub
End Class
UPDATE
from this i bind gridview
Public Function uplif() As DataTable
Dim dt As New DataTable()
gridvieew1.Visible = True
Try
dt.Columns.AddRange(New DataColumn(1) {New DataColumn("ID", GetType(Integer)),
New DataColumn("Name", GetType(String))}
Dim Content As String = Request.Form(textbox1.UniqueID)
For Each row As String In Content .Split(ControlChars.Lf)
If Not String.IsNullOrEmpty(row) Then
dt.Rows.Add()
Dim i As Integer = 0
For Each cell As String In row.Split(ControlChars.Tab)
If i > 1 Then
labelmessage.Text = "More than 2 columns not Allowed !!"
textbox1.Text = ""
Else
If cell.Trim() = "" Then
cell = "0"
End If
dt.Rows(dt.Rows.Count - 1)(i) = cell
i += 1
End If
Next
End If
Next
gridvieew1.DataSource = dt
gridvieew1.DataBind()
Catch Ex As Exception
labelmessage.CssClass = "alertNo"
labelmessage.Text = Ex.Message
End Try
Return dt
End Function
Protected Sub PasteToGridView(sender As Object, e As EventArgs)
uplif()
End Sub
now when i try to add new row like this
Private Sub AddNewRowToGrid()
Dim dt As DataTable = uplif()
Dim NewRow As DataRow = dt.NewRow()
dt.Rows.Add(NewRow)
gridvieew1.DataSource = dt
gridvieew1.DataBind()
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddNewRowToGrid()
End Sub
this shows same output like add new row and replace previous data which is already in gridview and also this shows an error
Object reference not set to an instance of an object.
after click on add new row
ID Name
where as i want like this
ID Name
1 abc
2 def
(here new empty row when click on button )
As was pointed out in a comment to your post, the problem is in these two lines:
Dim dt As New DataTable()
...
gridview1.DataSource = dt
That creates a brand new DataTable and binds the grid view to it. You don't copy data over, and you don't alter the existing gridview's table.
The correct fix here would be to get the DataTable from the gridview's DataSource and make any changes you need to to that. Don't create a new DataTable.
Get the already assigned DataSource and then add the Row. Do not add columns as it will be already present in your datasource
Private Sub AddNewRowToGrid()
Dim dt As gridview1.DataSource
Dim NewRow As DataRow = dt.NewRow()
dt.Rows.Add(NewRow)
gridview1.DataSource = dt
gridview1.DataBind()
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddNewRowToGrid()
End Sub
im trying to get value(true or false) from database but i want to select from role(DropDownList) to display if had permission or not in section
dropdownlist and checkboxlist using entitdatasource
i try this ( DropdownList(ddlRole))
Protected Sub ddlRole_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddlRole.SelectedIndexChanged
Using context As New AGIP_dbModel.AGIP_dbEntities()
For Each oItem As ListItem In ckSection.Items()
Dim objPerm As tbl_permission = New tbl_permission()
oItem.Value = objPerm.pre_status
Next
End Using
End Sub
This how submite button work(Store in database)
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Using context As New AGIP_dbModel.AGIP_dbEntities()
Dim id As Integer = ddlRole.SelectedValue
Try
Dim obj = context.tbl_permission.Where(Function(u) u.role_id = id)
For Each permission As tbl_permission In obj.ToList
context.tbl_permission.DeleteObject(permission)
context.SaveChanges()
Next
Catch ex As Exception
End Try
For Each oItem As ListItem In ckSection.Items()
Dim objPerm As tbl_permission = New tbl_permission()
objPerm.role_id = ddlRole.SelectedValue
objPerm.pre_status = oItem.Selected
objPerm.section_id = oItem.Value
context.tbl_permission.AddObject(objPerm)
context.SaveChanges()
Next
Response.Redirect("permission.aspx")
End Using
End Sub
tbl_role
tbl_section
tbl_permission relationship with role and section
I'm not familiar with usage of Entity yet so I hope you can get what I'm trying to do here.
Also not sure if checkbox has a Caption or Text property, kindly check.
Protected Sub ddlRole_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddlRole.SelectedIndexChanged
Using context As New AGIP_dbModel.AGIP_dbEntities()
For Each oItem As ListItem In ckSection.Items()
Dim objPerm As tbl_permission = New tbl_permission()
If objPerm.section_name = oItem.Caption Then 'Check if the permission record is same with the caption of the current checkbox in iteration
oItem.Checked = objPerm.pre_status
End If
Next oItem
End Using
End Sub
You also need to modify your SQL query on returning the permission records to include the section_name if you haven't already.
Finally found The Answer:
Protected Sub ddlRole_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddlRole.SelectedIndexChanged
Using context As New BWJO_dbModel.BWJO_dbEntities
Try
For Each secTionItem As ListItem In ckSection.Items
secTionItem.Selected = False
For Each oItem As ListItem In ckSection.Items
Dim PermObj = context.tbl_permission.Any(Function(u) u.role_id = ddlRole.SelectedValue And u.permission_status = True And u.section_id = oItem.Value)
If PermObj = True Then
oItem.Selected = True
End If
Next
Next
Catch ex As Exception
End Try
End Using
End Sub
End Class
I have a Gridview filled by a dataTable, filled by a DataAdapter. That's how grid is initially loaded in Page_Load.
To add a search funcionality, I make the same but passing TextBox.Text as parameter to the SELECT... LIKE ... statement.
To add an edit funcionality(a button in every row) I need the previous data in the dataTable, and if I performed a search before editing I need only the result of the search in my dataTable.
The problem is, I don't know how to keep its value alive (persistent), and dataTable has 0 columns when I press teh edit button, so it doesn't display anything to edit.
I guess it happens because I'm using Using, and dataTable is probably getting cleaned after End Using.
In that case, whta can I do to fix it? I thought removing miconn.Close() but it doesn't solve anything, in fact, I don't know if connection is still open after End Using.
Code:
Dim con As New Connection
Dim table As New DataTable()
Private Sub fill_grid()
Using miconn As New SqlConnection(con.GetConnectionString())
Dim sql As String = "SELECT area,lider_usuario FROM AREA"
Using command As New SqlCommand(sql, miconn)
Using ad As New SqlDataAdapter(command)
ad.Fill(table)
GridView1.DataSource = table
GridView1.DataBind()
'miconn.Close()
End Using
End Using
End Using
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
fill_grid()
End If
End Sub
Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Dim miCon As New Connection
Using miconn As New SqlConnection(miCon.GetConnectionString())
Dim sql As String = "SELECT area,lider_usuario FROM AREA WHERE area LIKE #area"
Using command As New SqlCommand(sql, miconn)
command.Parameters.Clear()
command.Parameters.Add("#area", SqlDbType.VarChar).Value = "%" + TextBox1.Text + "%"
Using ad As New SqlDataAdapter(command)
ad.Fill(table)
GridView1.DataSource = table
GridView1.DataBind()
'miconn.Close()
End Using
End Using
End Using
End Sub
Protected Sub EditRow(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
GridView1.DataSource = table
GridView1.DataBind()
End Sub
Protected Sub CancelEditRow(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
GridView1.EditIndex = -1
GridView1.DataSource = table
GridView1.DataBind()
End Sub
BindGrid()
{
var dt = YourMethodReturningDatatable();
ViewState["Table"] = dt;
grid.DataSource = ViewState["Table"];
grid.Databind();
}
page_load
{
if(not ispostback) // not because my 1 key stopped working.
{
BindGrid();
}
}
I would suggest you to make two different functions for filling the data table and binding it. Call the filling function before the !IsPostBack condition and do the binding inside the condition. Here is the sample code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim table as new DataTable
table = GetData() 'The function that would return a data table
If Not IsPostBack Then
GridView1.DataSource = table
GridView1.DataBind()
End If
End Sub
Private Function GetData() As DataTable
Using miconn As New SqlConnection(con.GetConnectionString())
Dim sql As String = "SELECT area,lider_usuario FROM AREA"
Using command As New SqlCommand(sql, miconn)
Using ad As New SqlDataAdapter(command)
ad.Fill(table)
GetData = table
miconn.Close()
End Using
End Using
End Using
End function
Hope it helps.