How to databind a repeater from stored procedure? - asp.net

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....

Related

dropdownList doesn't displays selected value

I am new at asp.net. I have a dropdownList which displays all categories for a specific article. The problem is that when I want to edit an article it doesn't displays the value that exists as default selected in dropdownList.
protected void datalist2_OnItemCreated(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.EditItem)
{
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection con = new SqlConnection(connection);
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id";
drpdKategoria.DataTextField = "emertimi";
drpdKategoria.DataBind();
drpdKategoria.SelectedValue = drpdKategoria.Items.FindByText(Qry).Value;
//drpdKategoria.Items.FindByValue(string val).Selected = true;
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
}
EditArtikull.aspx
<asp:Label ID="Label5" runat="server" style="font-weight: 700">Kategoria</asp:Label>
<fieldset>
<asp:DropDownList ID="drpdKategoria" runat="server" AutoPostBack="false"></asp:DropDownList>
</fieldset>
<br/>
ERROR:SystemNullReference Exception {"Object reference not set to an instance of an object."}
This line probably isn't going to find anything:
drpdKategoria.Items.FindByText(Qry)
Since Qry is a SQL statement:
string Qry = "select * from kategoria";
And I'm assuming that the display values in your DropDownList aren't SQL queries. Thus, when you call .Value on that first line, you're trying to de-reference something that isn't found (which is null), hence the error.
What item are you actually trying to find? If you want to select a default item, you need to be able to identify that item in some way. In your data that would be either by a known id value or a known emertimi value. For example, if you have a known emertimi value, it would be:
drpdKategoria.SelectedValue = drpdKategoria.Items.FindByText("some known value").Value
To make this a little more robust, you probably want to add some null checking. Something like this:
var defaultValue = drpdKategoria.Items.FindByText("some known value");
if (defaultValue != null)
drpdKategoria.SelectedValue = defaultValue.Value

How to declare a datasource in VB.NET?

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()

how do i display the "On Offer" indicator when the product is on offer in the database of asp.net?

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.

Unable to format date in dataset column,GridView

I am reading data from an excel sheet and displaying it in a data gridview.There are some date columns in the excel.So when i read the data from the excel and bind it to the dataGridView.The date is displayed in the format "02/02/2009 12:00:00 AM" but the actual data in the excel column is in the format "2/2/2009".So how to change the date format in the datagridview.
Since i am binding the data from the dataset i dont have any template columns or bound column set so i dont know where to set the HtmlEncode="False" DataFormatString = "{0:T}"
Is there any way to do this.Please help me.
Please find the below code sample.
string OleDbConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= "+ FileUpload1.PostedFile.FileName + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
string strSheetName = "Sheet1";
OleDbConnection oledbConnection;
OleDbCommand oledbCommand;
OleDbDataAdapter oledbAdapter;
oledbCommand = new OleDbCommand();
oledbAdapter = new OleDbDataAdapter();
DataSet dsExcellData = new DataSet();
oledbConnection = new OleDbConnection(OleDbConnection);
oledbConnection.Open();
oledbCommand.Connection = oledbConnection;
oledbCommand.CommandText = "Select * from [" + strSheetName + "$]"; // i want to find this sheet name
oledbAdapter.SelectCommand = oledbCommand;
oledbAdapter.Fill(dsExcellData);
oledbConnection.Close();
GridView1.DataSource = dsExcellData.Tables[0];
GridView1.DataBind();
==========================================================
I tried the
dsExcellData.Tables[0].Rows[rowcount]["date_column"].ToString()] = dsExcellData.Tables[0].Rows[rowcount]["date_column"].ToString()].ToString("d");
but the value is not getting assigned as "mm/dd/yyyy" It is also taking the time default time again (mm/dd/yyyy hh:mm:ss AM).
=============================================================
I am just assigning the data set to the gridview.The problem is the dataset is reading the date column in the format mm/dd/yyyy hh:mm:ss AM.I am unable to change the data in the dataset also.
=============================================================
Finaly i got the answer from ScottE:
we have to add the below code in the itemdatabound of the datagridview :
protected void dgValidatedData_ItemDataBound1(object sender, DataGridItemEventArgs e)
{
for (int i = 0; i <= e.Item.Cells.Count - 1; i++)
{
System.DateTime cellDate = default(System.DateTime);
if (System.DateTime.TryParse(e.Item.Cells[i].Text, out cellDate))
{
e.Item.Cells[i].Text = string.Format("{0:d}", cellDate);
}
}
}
Ok, try this, where "Item" is the column name (could be multiple) that is a date that needs formatting. This is of course vb.net, but you can sort that out. I'm sure there's a better way, but this works.
Protected Sub gv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
For i As Integer = 0 To e.Row.Cells.Count - 1
If gv.HeaderRow.Cells(i).Text = "Item" Then
e.Row.Cells(i).Text = String.Format("{0:d}", CType(e.Row.Cells(i).Text, Date))
End If
Next
End If
End Sub
Or, if you don't know what columns will have dates, the following will work as well:
Protected Sub gv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
For i As Integer = 0 To e.Row.Cells.Count - 1
Dim cellDate As Date
If Date.TryParse(e.Row.Cells(i).Text, cellDate) Then
e.Row.Cells(i).Text = String.Format("{0:d}", cellDate)
End If
Next
End If
End Sub
If you're binding it as a asp:BoundField you'll need to set htmlencode to false.
<asp:BoundField HtmlEncode="false" DataField="Blah" DataFormatString="{0:d}" />
Date format you should define in your GridView column. For example:
<asp:GridView>
...
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Date", "{0:T}") %>'></asp:Label>
</ItemTemplate>
...
</asp:GridView>
Here is a solution using a custom control that derives from GridView:
using System;
using System.Collections;
using System.Web.UI.WebControls;
namespace CustomControls {
public class FormattedGridView : GridView {
protected override ICollection CreateColumns(PagedDataSource dataSource, bool useDataSource) {
// Call base method and return the collection as an ArrayList
var columns = (ArrayList) base.CreateColumns(dataSource, useDataSource);
for (var i = 0; i < columns.Count; i++) {
var agf = columns[i] as AutoGeneratedField;
if (agf != null && agf.DataType == typeof(DateTime)) {
// create a new column because the AutoGeneratedField does not support
// the modification of the DataFormatString property
var bf = new BoundField();
// copy some of the original properties
bf.DataField = agf.DataField;
bf.HeaderText = agf.HeaderText;
bf.HtmlEncode = false;
// set the format for the DateTime types
bf.DataFormatString = "{0:T}";
// replace the existing auto-generated colums
columns[i] = bf;
}
}
return columns;
}
}
}
Finaly i got the answer from ScottE:
we have to add the below code in the itemdatabound of the datagridview :
protected void dg_ItemDataBound1(object sender, DataGridItemEventArgs e)
{
for (int i = 0; i <= e.Item.Cells.Count - 1; i++)
{
System.DateTime cellDate = default(System.DateTime);
if (System.DateTime.TryParse(e.Item.Cells[i].Text, out cellDate))
{
e.Item.Cells[i].Text = string.Format("{0:d}", cellDate);
}
}
}
But the above code will check all the data that is bound to the datagrig.It will try to parse the data as datetime in the cell.If it is a valid datetime then it will convert the data into the format which we applied.

how to clear off gridview?

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);
}

Resources