I wrote an ASPX file in VB.NET. Originally this file ran successfully but after adding one additional parameter it now fails on "Name 'peType' is not declared".
This error does not make sense to me though because I have similar parameter, 'dType', which it does not error on. What is the cause of this error?
Here is some of my ASPX code file:
Sub Page_Load(Sender as Object, E as EventArgs)
If Not IsPostback Then
Dim TheMonthDate As Date = DateAdd(DateInterval.Month, -1, Today)
calStartDate.SelectedDate = CDate((TheMonthDate.Month) & "/1/" & Year(TheMonthDate)).ToString("MM/dd/yyyy")
calEndDate.SelectedDate = GlobalFunctions.GlobalF.MonthLastDate(CDate((TheMonthDate.Month) & "/1/" & Year(TheMonthDate)).ToString("MM/dd/yyyy"))
Dim arrType as New ArrayList()
Dim arrOrgUnit as New ArrayList()
Dim arrPEType as New ArrayList()
Dim peType As ListBox
arrType.Add("Product and Process")
arrType.Add("Product")
arrType.Add("Process")
dType.DataSource = arrType
dType.DataBind()
arrPEType.Add("-INC")
arrPEType.Add("-NC")
arrPEType.Add("-QC")
peType.DataSource = arrPEType
'peType.DataTextField = "DisplayColumnName"
'peType.DataValueField = "ValueColumnName"
peType.DataBind()
...
Dim TheType as String
Dim TheOrgUnit as String
Dim PE_Type as String
Select Case dType.SelectedValue
Case "Product and Process":
TheType = "((SMARTSOLVE.V_QXP_ALL_EXCEPTION.QXP_BASE_EXCEPTION)='PXP_PRODUCT_QXP' Or (SMARTSOLVE.V_QXP_ALL_EXCEPTION.QXP_BASE_EXCEPTION)='PXP_PROCESS_QXP')"
Case "Product":
TheType = "((SMARTSOLVE.V_QXP_ALL_EXCEPTION.QXP_BASE_EXCEPTION)='PXP_PRODUCT_QXP')"
Case "Process":
TheType = "((SMARTSOLVE.V_QXP_ALL_EXCEPTION.QXP_BASE_EXCEPTION)='PXP_PROCESS_QXP')"
End Select
Select Case peType.SelectedValue
Case "INC":
PE_Type = "substring(a.QXP_EXCEPTION_NO, charindex('-', a.QXP_EXCEPTION_NO)+1, 4)='INC'"
Case "NC":
PE_Type = "substring(a.QXP_EXCEPTION_NO, charindex('-', a.QXP_EXCEPTION_NO)+1, 4)='NC'"
Case "QC":
PE_Type = "substring(a.QXP_EXCEPTION_NO, charindex('-', a.QXP_EXCEPTION_NO)+1, 4)='QC'"
End Select
...
<td>
Product Exception Type:
</td>
<td>
<ASP:DROPDOWNLIST ID="peType" RUNAT="Server" AUTOPOSTBACK="true" />
</td>
But now my error is:
Object reference not set to an instance of an object
You missed setting the DataTextField and DataValueField property, when you tried to bind DataSource to your Dropdownlist, so set as follows:
peType.DataSource = arrPEType
peType.DataTextField = "DisplayColumnName"
peType.DataValueField = "ValueColumnName"
peType.DataBind()
Related
this may sound like a silly question but i am learning Visual Basic ASP.NET 4 and i have been asked to create a DropDownList which obtains information from a table using SQL. I cant seem to pull the selected item from the dropdownlist and show it on the screen using Request.Form.
I have tried this..
Dim selItem As String = Request.Form("DDList")
Response.Write(selItem)
but this does not show anything on screen. Please help as i am struggling with this.
I have added my dropdownlist as follows:
<asp:DropDownList ID="DDList" runat="server" Width="201px">
</asp:DropDownList>
<asp:DropDownList ID="DDList2" runat="server" Width="145px">
</asp:DropDownList>
My Class/Function
Public Class sqlFunc
Public Shared Function tableData() As DataSet
Dim oraConnect As New OracleConnection
oraConnect.ConnectionString = ConfigurationManager.ConnectionStrings("smart_dev").ConnectionString
Dim oraCommand As New OracleCommand
oraCommand.Connection = oraConnect
oraCommand.CommandType = Data.CommandType.Text
Dim lsSQL As String = ""
lsSQL = "SELECT code, description FROM ref_code WHERE domain = 'SPECIALTY'"
oraCommand.CommandText = lsSQL
Dim da As New OracleDataAdapter(oraCommand)
Dim ds As New DataSet
da.Fill(ds)
Return ds
End Function
What i am using on my .aspx.vb page;
Dim dsData1 As New DataSet
dsData1 = tableData()
DDList.DataSource = dsData1
DDList.DataValueField = "code"
DDList.DataTextField = "description"
DDList.DataBind()
DDList.Items.Insert(0, New ListItem(String.Empty, String.Empty))
DDList.SelectedIndex = 0
You don't need to get the selected value using Request.Form if you are using an asp:DropDown ASP.net control. All you have to do is:
Dim selItem As String = DDList.SelectedValue
Response.Write(selItem)
If you really want to use Request.Form, do it like this:
Dim selItem As String = Request.Form(DDList.ClientID)
Response.Write(selItem)
Also, make sure you have ViewState enabled and that you do not rebind the DropDown at PageLoad when there is a PostBack:
Sub Page_Load
If Not IsPostBack
' Bind your DropDown here
End If
End Sub
I have an Editable GridView control that functions off of an XML file. The GridView contains an empty-data-template given that the xml file contains no data on page load. The empty-data-template consist of two textbox controls and a link-button for placing data into the xml file, and thus should cause the Gridview to display. My problem is that when I click the link button, I get an Object-reference related error in response to this line: Dim oDr As DataRow = oDs.Tables("po").NewRow ...the full event handler, I provided below:
The code behind:
Public Sub writeStartpoNum()
Dim startpoNumID As String = DirectCast(gvPurchaseOrderNum.Controls(0).Controls(0).FindControl("txtStartpoNumID"), TextBox).Text
Dim startpoNum As String = DirectCast(gvPurchaseOrderNum.Controls(0).Controls(0).FindControl("txtStartpoNum"), TextBox).Text
Dim oDs As New DataSet()
Dim xmlPath As String = MapPath("~/xml/newShipment.xml")
If Not System.IO.File.Exists(xmlPath) Then
oDs.DataSetName = "newShipmentNotification"
oDs.Tables.Add("pos")
oDs.Tables("pos").Columns.Add("pos_Id")
oDs.Tables("pos").Columns("pos_Id").ColumnMapping = MappingType.Hidden
oDs.Tables.Add("po")
oDs.Tables("po").Columns.Add("ponumberID")
oDs.Tables("po").Columns.Add("pos_Id")
oDs.Tables("po").Columns("pos_Id").ColumnMapping = MappingType.Hidden
oDs.Tables("po").Columns.Add("ponumber")
Dim pos_po As DataRelation = oDs.Relations.Add("pos_po", oDs.Tables("pos").Columns("pos_Id"), _
oDs.Tables("po").Columns("pos_Id"))
pos_po.Nested = True
Dim oDrs As DataRow = oDs.Tables("pos").NewRow
oDrs("pos_Id") = 0
oDs.Tables("pos").Rows.Add(oDrs)
Else
oDs.ReadXml(Server.MapPath("~/xml/newShipment.xml"))
End If
Dim oDr As DataRow = oDs.Tables("po").NewRow
oDr("ponumberID") = startpoNumID
oDr("ponumber") = startpoNum
oDr("pos_Id") = 0
oDs.Tables("po").Rows.Add(oDr)
oDs.WriteXml(Server.MapPath("~/xml/newShipment.xml"))
gvPurchaseOrderNum.DataSource = oDs.Tables("po")
gvPurchaseOrderNum.DataBind()
End Sub
...this is the design for the empty-data-template in the Gridview:
<emptydatatemplate>
<b>Enter Purchase Order Number:</b> <br />
<asp:TextBox ID="txtStartpoNumID" runat="server"></asp:TextBox>
<asp:TextBox ID="txtStartpoNum" runat="server"></asp:TextBox><br />
<asp:LinkButton ID="lnkpro" runat="server" OnClick="writeStartpoNum" Text="Add Purchase order Number"></asp:LinkButton>
<br /><br />
</emptydatatemplate>
...this is how the xml reflects on page load as a results of a function that clears the xml file of any data if the xml file contains data on page load.
<?xml version="1.0" standalone="yes"?>
<newShipmentNotification>
<pos />
</newShipmentNotification>
...As I mentioned, when debugged - the issue stems from the following line
Dim oDr As DataRow = oDs.Tables("po").NewRow
The xml is build out, via the conditional statement. What I cannot figure is why the dataset variable (oDs), even though it reflects the pos table when viewed in debug mode, still generates an object-reference related error. Please provide some direction as to what I may be doing wrong here or if there is something I'm missing. Thanks
The issue is when you have the xml file without 'po' node. You can move the node to a new
method like:
Private Function CreatePOSDataset() As DataSet
Dim oDs As New DataSet()
oDs.DataSetName = "newshipmentnotification"
oDs.Tables.Add("pos")
oDs.Tables("pos").Columns.Add("pos_Id")
oDs.Tables("pos").Columns("pos_Id").ColumnMapping = MappingType.Hidden
oDs.Tables.Add("po")
oDs.Tables("po").Columns.Add("ponumberID")
oDs.Tables("po").Columns.Add("pos_Id")
oDs.Tables("po").Columns("pos_Id").ColumnMapping = MappingType.Hidden
oDs.Tables("po").Columns.Add("ponumber")
Dim pos_po As DataRelation = oDs.Relations.Add("pos_po", oDs.Tables("pos").Columns("pos_Id"), _
oDs.Tables("po").Columns("pos_Id"))
pos_po.Nested = True
Dim oDrs As DataRow = oDs.Tables("pos").NewRow
oDrs("pos_Id") = 0
oDs.Tables("pos").Rows.Add(oDrs)
CreatePOSDataset = oDs
End Function
And call the method when 'po' node does not exist:
Public Sub writeStartpoNum(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim startpoNumID As String = DirectCast(gvPurchaseOrderNum.Controls(0).Controls(0).FindControl("txtStartpoNumID"), TextBox).Text
Dim startpoNum As String = DirectCast(gvPurchaseOrderNum.Controls(0).Controls(0).FindControl("txtStartpoNum"), TextBox).Text
Dim oDs As New DataSet()
Dim xmlPath As String = MapPath("~/xml/newshipmentnotification.xml")
If Not System.IO.File.Exists(xmlPath) Then
oDs = CreatePOSDataset()
Else
oDs.ReadXml(Server.MapPath("~/xml/newshipmentnotification.xml"))
If oDs.Tables("po") Is Nothing Then
oDs = CreatePOSDataset()
End If
End If
Dim oDr As DataRow = oDs.Tables("po").NewRow
oDr("ponumberID") = startpoNumID
oDr("ponumber") = startpoNum
oDr("pos_Id") = 0
oDs.Tables("po").Rows.Add(oDr)
oDs.WriteXml(Server.MapPath("~/xml/newshipmentnotification.xml"))
gvPurchaseOrderNum.DataSource = oDs.Tables("po")
gvPurchaseOrderNum.DataBind()
End Sub
I'm trying to databind my repeater but so far not having any luck. Anyone think that can show me where I'm going wrong? I have two functions at the moment by following some tutorials/examples but I was hoping to have just one... maybe not possible. Thanks!
HTML:
<ItemTemplate>
<tr class="row">
<td><asp:Label ID="TitleLabel" runat="server" Text=""></asp:Label></td>
<td><asp:Label ID="NameLabel" runat="server" Text=""></asp:Label></td>
<td><asp:Label ID="PhoneLabel" runat="server" Text=""></asp:Label></td>
<td><asp:Label ID="EmailLabel" runat="server" Text=""></asp:Label></td>
</tr>
</ItemTemplate>
VB
Protected Sub BindData()
Dim oCommand As SqlCommand
Dim oReader As SqlDataReader
Try
oCommand = DataAccess.GetSQLCommand("People_Retrieve", CommandType.StoredProcedure, SourceServer.ConnectionLocal)
oCommand.Connection.ChangeDatabase("MyDatabase")
oCommand.CommandTimeout() = 9000
oReader = oCommand.ExecuteReader()
PeopleRepeater.DataSource = oReader
PeopleRepeater.DataBind()
Catch ex As Exception
ErrorHandler.HandleError(ex)
Finally
oReader.Close()
oReader = Nothing
End Try
End Sub
Protected Sub PeopleRepeater_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles PeopleRepeater.ItemDataBound
Dim NameLabel As Label = CType(e.Item.FindControl("LabelName"), Label)
NameLabel.Text = e.Item.DataItem("Name")
Dim TitleLabel As Label = CType(e.Item.FindControl("TitleName"), Label)
NameLabel.Text = e.Item.DataItem("Title")
Dim PhoneLabel As Label = CType(e.Item.FindControl("PhoneName"), Label)
NameLabel.Text = e.Item.DataItem("Phone")
Dim EmailLabel As Label = CType(e.Item.FindControl("EmailName"), Label)
NameLabel.Text = e.Item.DataItem("Email")
End Sub
Use a SqlDataAdapter:
Using adap As New SqlDataAdapter(oCommand)
Dim table As New DataTable()
adap.Fill(table)
PeopleRepeater.DataSource = table
PeopleRepeater.DataBind()
End Using
I don't see where you're opening the connection either, so you might need to add that:
oCommand.Connection.Open()
Follow the steps
Create the stored procedure named as 'SelectPersonalDetails'
CREATE PROCEDURE SelectPersonalDetails
-- Add the parameters for the stored procedure here
#Email SYSNAME
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
BEGIN TRY
BEGIN TRANSACTION
BEGIN
SELECT Name,Title,Phone,Email FROM PersonalDetails
WHERE
Email = #Email
END
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
DECLARE #ERR AS VARCHAR(500)
SELECT #ERR = ERROR_MESSAGE()
RAISERROR(#ERR,16,1)
RETURN
END CATCH
END
Create dataset in order to bind the data in the repeater.
public DataSet Get_PersonaldetailbasedEmail()
{
try
{
DataSet oDS = new DataSet();
SqlParameter[] oParam = new SqlParameter[1];
oParam[0] = new SqlParameter("#Email", _sEmail);
oDS = SqlHelper.ExecuteDataset(DataConnectionString, CommandType.StoredProcedure, "SelectPersonalDetails", oParam);
return oDS;
}
catch (Exception e)
{
ErrorMessage = e.Message;
return null;
}
}
Note: (i) SelectPersonalDetails is the stored procedure name
(ii) In order to select unique record from the table i have used emailid
(iii) I have assume the table name as PersonalDetails.
Create a user control page something like Personeldetails.ascx
/li>
/li>
/li>
/li>
Note above i have the html code for repeater but i don't know how to work around in this editor. anyways repeater id is same as your repeater and label ids are same as your label id.
Databind
Create a function to bind the data
public void FillArray(ArrayList alist)
{
ArrayList al = new ArrayList();
foreach (Object objRow in alist)
{
string sTitle = ((DataRow)objRow)["Title"].ToString();
string sName = ((DataRow)objRow)["Name"].ToString();
string sPhone = ((DataRow)objRow)["Phone"].ToString();
string sMail = ((DataRow)objRow)["Mail"].ToString();
al.Add(new string[]{ sTitle,sName,sPhone,sMail});
}
PeopleRepeater.DataSource = al;
PeopleRepeater.DataBind();
}
Now called Item databound
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
string[] itemArray = ((string[])e.Item.DataItem);
Label myTitle = (Lable)e.Item.FindControl("TitleLabel");
Label myName = (Label)e.Item.FindControl("NameLabel");
Label myPhone = (Label)e.Item.FindControl("PhoneLabel");
Label myEmail = (Label)e.Item.FindControl("EmailLabel");
myTitle.Text = itemArray[0];
myName.Text = itemArray[1];
myPhone.Text = itemArray[2];
myEmail.Text = itemArray[3];
}
If you find the answer useful, please mark it as your answer else let me know....
I need to display the "on Offer" indicator next to the product in the gridview if the product has a number "1" in the "Offered" column in the database. if it is zero, then don't display. is there some way to achieve that? thanks.
In my product listing page:
Dim objCat As New Category
Dim objProduct As New Product
Dim i As Integer
Dim boolError As Boolean = False
objCat.ID = CType(Request.QueryString("CatID"), Integer)
' get details of the category
objCat.GetDetails()
' Display the category name
lblCatName.Text = objCat.Name
lblCatName2.Text = objCat.Name
' Display the category description
lblCatDesc.Text = objCat.Description
objCat.GetOfferedProducts()
For i = 0 To gvProduct.Rows.Count - 1
' Get the ProductId from the first cell
objProduct.ID = gvProduct.Rows(i).Cells(0).Text
Dim lblOffer As Label
lblOffer = CType(gvProduct.Rows(i).FindControl("lblOffer"), Label)
If objCat.Offered = "1" Then
lblOffer.Visible = True
Else
lblOffer.Visible = False
End If
Next
gvProduct.DataSource = objCat.GetProducts()
gvProduct.DataBind()
in my category class:
Public Sub GetOfferedProducts()
' Define a conection to database
' Read connection string from the web.config file.
Dim strConn As String
strConn = ConfigurationManager.ConnectionStrings("AppDb").ToString
Dim conn As New SqlConnection(strConn)
' Retrieve details of a given Category ID from the database
Dim strSql As String
strSql = "SELECT * FROM CatProduct cp INNER JOIN Product p " & _
"ON cp.ProductID=p.ProductID INNER JOIN Category c ON cp.CategoryID=c.CategoryID " & _
"WHERE cp.CategoryID=#CategoryID"
' Define an Command object to execute the SQL statement
Dim cmd As New SqlCommand(strSql, conn)
' Add parameter to the SQL command
cmd.Parameters.AddWithValue("#CategoryID", ID)
' Define a data adapter to fetch data
Dim da As New SqlDataAdapter(cmd)
' Define a data set to hold the data fetched
Dim ds As New DataSet
' Open database connection
conn.Open()
da.Fill(ds, "CatProduct")
' Close the database connection
conn.Close()
If ds.Tables("CatProduct").Rows.Count <> 0 Then
Name = ds.Tables("CatProduct").Rows(0)("CatName")
Description = ds.Tables("CatProduct").Rows(0)("CatDesc")
ImageFile = ds.Tables("CatProduct").Rows(0)("CatImage")
Offered = CType(ds.Tables("CatProduct").Rows(0)("Offered"), Integer)
End If
I would hook up the gridview's OnRowDataBound in your aspx page:
<asp:gridview id="MyGridView"
autogeneratecolumns="true"
allowpaging="true"
onrowdatabound="MyGridView_RowDataBound"
runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" id="lblOffer"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
Then in the code behind you could do something like this:
void MyGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var lbl = e.Row.FindControl("lblOffer");
If objCat.Offered = "1" Then
lbl.Visible = True
Else
lbl.Visible = False
End If
}
}
Hope that helps!!
There are various ways to make this happen. Basically, you're just looking to conditionally show/hide an element in the grid.
Which of the many ways to do this happens to be the best way entirely depends on how you're retrieving, binding to and displaying your data. You can put the logic in the business layer (a certain property is set or null based on business rules, etc.), in your data binding code (if you're looping through records for the display or something, such as in an ItemDataBound handler), in your display code (if you're just declaring everything in the aspx and just need to toss in an Eval and a conditional), etc.
I'm creating a dynamic gridview function which will bind different tables from DB into a datatable and then assign the datatable to the gridview! This is how it works, i have a dropdownlist, gridview and a button, the button will fire specific function based on the dropdownlist selection and then gridview will bind the data, my problem is that, when u press the button for the 1st time, the gridview will bind the data from DB, for second time pressing, the gridview will duplicate the data from the data of 1st time pressing! how do i clear off the gridview to avoid data duplication?
Private Sub Login()
sSql = "" & _
"SELECT TYPE, SUBTYPE, LOGTS, ACTION, USERID, STAT1 " & _
"FROM i_LOG " & _
"WHERE TYPE = 'USR' AND SUBTYPE = 'LOG' " & _
"AND CONVERT(VARCHAR(20), LOGTS, 103) >= '" & txtDTFrom.Text & _
"' AND CONVERT(VARCHAR(20), LOGTS, 103) <= '" & txtDTTo.Text & "'"
DT = CreateDataTable(sSql) 'Retrieve from database.
Session(sSesDT) = DT
GVM.DataTable = DT
GVM.GVAddEmptyRow()
Dim seq As New BoundField
Dim Type As New BoundField
Dim SubType As New BoundField
Dim Logts As New BoundField
Dim action As New BoundField
Dim user As New BoundField
Dim status As New BoundField
seq.HeaderText = GVM.DTNumberField
seq.DataField = GVM.DTNumberField
Type.HeaderText = "Type"
Type.DataField = "TYPE"
SubType.HeaderText = "Subtype"
SubType.DataField = "SUBTYPE"
Logts.HeaderText = "Date and Time"
Logts.DataField = "LOGTS"
action.HeaderText = "Action"
action.DataField = "ACTION"
user.HeaderText = "User ID"
user.DataField = "USERID"
status.HeaderText = "Status"
status.DataField = "STAT1"
gv.AutoGenerateColumns = False
gv.Columns.Add(Type)
gv.Columns.Add(SubType)
gv.Columns.Add(Logts)
gv.Columns.Add(action)
gv.Columns.Add(user)
gv.Columns.Add(seq)
gv.Columns.Add(status)
gv.DataSource = Session(sSesDT)
gv.DataBind()
End Sub
Private Overloads Function CreateDataTable(ByVal sSql As String) As DataTable
Dim DA As New OleDb.OleDbDataAdapter
Dim dtDataTbl As New DataTable
Dim dcDataCol As New DataColumn
With DBMgr
.openCnn()
.SQL = sSql
.openRst()
DA.Fill(dtDataTbl, .rst)
End With
'==Adding Columns==
dcDataCol = New DataColumn 'No
With dcDataCol
.DataType = GetType(Int32)
.ColumnName = GVM.DTNumberField
.AutoIncrement = True
'.AllowDBNull = True
End With
dtDataTbl.Columns.Add(dcDataCol)
'**Adding Columns**
Return dtDataTbl
End Function
Sorry, this is in C#, but just call it before you bind any new data and it'll clear any existing data... unless of course the problem is that the DataSource you are assigning has the duplicated data.
gridview.DataSource=null;
gridview.DataBind();
Also, just to note, you are adding every column in every time that procedure is called? You need to run:
gridview.Columns.Clear();
You can reset it's data source and rebind it for example
gv.datasource=""
gv.databind()
and then reuse it
Usually this does not happen when you rebind grid like:
grid.DataSource = 'NEW_DATA_SOURCE'
grid.DataBind
I think may be the problem is in your function fetching data:
CreateDataTable(sSql)
Please check inside this if you are fetching data every time into a new DataTable or using same one (may be declared at global scope or passed from your class to data accessing component). I'd lost whole night once to fix this :(
Place your gridview in a table with an id:
<table id="myTable" border="0">
<tr><td>
<asp:GridView Width="765px" ID="mygrid" runat="server">
...
...
</asp:GridView>
</td></tr></table>
Then call from a button click your javascript function:
function clearGridview()
{
var rows = document.getElementById('myTable').getElementsByTagName('tbody') [0].getElementsByTagName('tr').length;
if(rows!=0)
document.getElementById("myTable").deleteRow(0);
}