itemdatabound event of a nested listview - asp.net

I have a nested listview which I databind on the parent 'ItemDataBound' event, but how do i access/register the nested listview's itemdatabound event?
Thanks!
Edits
My parent listview itemdatabound now looks like so,
Protected Sub lvwManagePolicy_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles lvwManagePolicy.ItemDataBound
If e.Item.ItemType = ListViewItemType.DataItem Then
Dim rv As DataRowView = CType(e.Item.DataItem, DataRowView)
Me.dsAccoutnTransactionHistory = Wrap.getWrapAccountTransactionHistory(rv!PLATFORM_ID, False)
Dim lvwTransactionHistory As ListView = DirectCast(e.Item.FindControl("lvwTransactionHistory"), ListView)
lvwTransactionHistory.ItemDataBound += New EventHandler(Of ListViewItemEventArgs)(lvwTransactionHistory_ItemDataBound)
lvwTransactionHistory.DataSource = dsAccoutnTransactionHistory
lvwTransactionHistory.DataBind()
End If
End Sub
but i get an error
BC32022: 'Public Event ItemDataBound(sender As Object, e As
System.Web.UI.WebControls.ListViewItemEventArgs)' is an event, and
cannot be called directly. Use a 'RaiseEvent' statement to raise an
event.

Before assigning the data to nested control in your parent control you can register the event like below under your parent ItemBoundData
ListView f = new ListView();
f.ItemDataBound += new EventHandler<ListViewItemEventArgs>(f_ItemDataBound);
protected void f_ItemDataBound(object sender, ListViewItemEventArgs e)
{
}

You can this :
<asp:ListView onitemcommand="inner_ItemCommand" ...
protected / public item command method need :
public void inner_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandArgument == "delete")
{
//do delete here
}
}

Related

Gridview AutoGeneratingColumn Event?

The .NET DataGrid control has an AutoGeneratingColumn Event that fires once for every bound data item right after the data source is changed. This is useful because you could define certain columns in the template, like so:
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="ID" DataNavigateUrlFormatString="ww{0}" DataTextField="ID" DataTextFormatString="{0}" HeaderText="ID" />
</Columns>
and then prevent the same column from being replicated when columns are autogenerated from your data source. In this example, you could prevent the ID column from being autogenerated like this:
Private Sub DG_AutoGeneratingColumn(ByVal sender As Object, ByVal e As DataGridAutoGeneratingColumnEventArgs)
Dim headername As String = e.Column.Header.ToString()
If headername = "ID" Then
e.Cancel = True
End If
End Sub
My question is whether a similar functionality can be achieved with a GridView control.
DETAILS
The data source for the gridview is a DataTable object, which I am binding like so:
GridView1.DataSource = results.Tables("Vitals")
GridView1.DataBind()
The number of columns in my DataTable will vary, which is why it is extremely convenient for me to use AutoGenerateColumns.
To do that you should handle the RowCreated event and write something like the following:
private List<int> hideColumnsIndexes = new List<int>();
protected void Page_Load(object sender, EventArgs e)
{
hideColumnsIndexes.Clear();
}
protected void GridView1_OnRowCreated(object sender, GridViewRowEventArgs e)
{
//Find indexes
if (e.Row.RowType == DataControlRowType.Header)
{
for (int i = 0; i < e.Row.Cells.Count; i++ )
{
if (e.Row.Cells[i].Text == "Id")
{
hideColumnsIndexes.Add(i);
}
//Add more columns to hide
}
}
//Hide cells
foreach (var index in hideColumnsIndexes)
{
e.Row.Cells[index].Visible = false;
}
}

refresh gridview after search

I have a search on a grid view which limits the results. I would like the grid view to repopulate with all entries if a. the search box is empty or b. the user hits a button to refresh.
Protected Sub btnSeach_Click(sender As Object, e As EventArgs) Handles btnSeach.Click
StaffDetailsStaffGridView.DataSourceID = ""
StaffDetailsStaffGridView.DataSource = ObjectDataSource1
StaffDetailsStaffGridView.DataBind()
If txtFnameSearch.text = " " Then
StaffDetailsStaffGridView.DataBind()
End If
End Sub
Protected Sub btnRefreshSearch_Click(sender As Object, e As EventArgs) Handles btnRefreshSearch.Click
StaffDetailsStaffGridView.DataBind()
End Sub
End Class
StaffDetailsStaffGridView.DataBind() obviously doesn't work.
how do I do this properly?
The best way to repopulate the GridView is by having a method specifically for binding your data and calling when needed.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostback)
BindGrid();
}
private void BindGrid()
{
StaffDetailsStaffGridView.DataSource = ObjectDataSource1;
StaffDetailsStaffGridView.DataBind();
}
protected void btnRefreshSearch_Click(object sender, EventArgs e)
{
BindGrid();
}
protected void btnSeach_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(txtFnameSearch.text))
{
BindGrid();
}
}
I'm assuming you are filtering your data directly via the ObjectDataSource.
You should get the datasource again and set it as the DataSource and then bind again.
Something like this
Protected Sub btnRefreshSearch_Click(sender As Object, e As EventArgs) Handles btnRefreshSearch.Click
Dim searchKey as String
searchKey =txtFnameSearch.Text.Trim()
Dim staffSearchREsults=MyService.GetSearchResults(searchKey)
StaffDetailsStaffGridView.DataSource = staffSearchREsults
StaffDetailsStaffGridView.DataBind()
End Sub
Assuming MyService.GetSearchResults method will return you a valid search result based on the search key.
This will not work because, after postback, gridview's datasource will be lost. So you always need to set datasource before DataBind() is called.
StaffDetailsStaffGridView.DataSource = ObjectDataSource1
StaffDetailsStaffGridView.DataBind()
You can also save ObjectDataSource1 into session and use it later for binding:
Session["MyObjectDataSource"] = ObjectDataSource1;
...
Protected Sub btnRefreshSearch_Click(sender As Object, e As EventArgs) Handles btnRefreshSearch.Click
StaffDetailsStaffGridView.DataSource = Session["MyObjectDataSource"]
StaffDetailsStaffGridView.DataBind()
End Sub
If you're using a declarative datasource, you can just call DataBind() again on the GridView:
StaffDetailsStaffGridView.DataBind()

The GridView 'GridView1' fired event PageIndexChanging which wasn't handled

I have created:
one master page and one content page called Detail.
On Button click event, displaying data in grid view.
In grid view, columns are autogenerated.
I wanted to show 11 column in grid view, but it is more than page
size.
What to do for this?
I have created sql helper file for database connection code and calling that method, not using sqldatasource for connection.
When I trying to do paging, getting error:
The GridView 'GridView1' fired event PageIndexChanging which wasn't
handled.
You need to declare a method on your code behind that handles the PageIndexChanging event.
Something similar to this:
protected void GridView1_PageIndexChanging (object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindGridView(); //bindgridview will get the data source and bind it again
}
private void bindGridView()
{
GridView1.DataSource=getData();
GridView1.DataBind();
}
Providing sample code:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindGridView(); //bindgridview will get the data source and bind it again
}
protected void Page_Load(object sender , EventArgs e)
{
if(!IsPostBack)
bindGridView();
}
//this is some sample data
private void bindGridView()
{
DataTable t = new DataTable();
t.Columns.Add("Col1");
t.Columns.Add("Col2");
DataRow r = null;
for (int i = 0; i < 25; i++)
{
r = t.NewRow();
r.ItemArray = new object[] { "Val" + i, " Another " + i };
t.Rows.Add(r);
}
GridView1.DataSource = t;
GridView1.DataBind();
}
And this is the markup:
<asp:GridView OnPageIndexChanging="GridView1_PageIndexChanging" AllowPaging="true" PageSize="10" ID="GridView1" runat="server" AutoGenerateColumns="true">
Produces this:
For Paging you can use OnPageIndexChanging for this....
For Example
you have to use OnPageIndexChanging="gvdetails_PageIndexChanging" in your GridView...
You have to write below code into event in code behind like
protected void gvdetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvdetails.PageIndex = e.NewPageIndex;
BindData();
}
For more detail you can check the below link here I am using page Index change in my article...
Here I use PageIndexChange
I hope this will helps you....Share it with others...Thanks!
This is the final answer:
Imports System.Collections.Generic ' library
Protected Sub grdEmployees_PageIndexChanging1(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdEmployees.PageIndexChanging
grdEmployees.PageIndex = e.NewPageIndex
LoadEmployeeList() 'FUNCTION FOR DATASET
grdEmployees.DataBind()
End Sub
you simply add this to your code :
protected void GridViewTrsEmail_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridViewTrsEmail.PageIndex = e.NewPageIndex;
GridViewTrsEmail.DataBind();
}
To fix this, I had to take a closer look at my datasource and datakeys. I have a set of records that are returned from SQL Server and what I was doing is binding them to a POCO. This class had several public properties of type Integer. These Integers were my datakeys on the grid. I replaced their type with a string instead to bypass the casting issue.

Handle Click Event for LinkButton in User Control from Parent ASP.NET page

I have a LinkButton within a User Control and it has handled with:
Private Sub LoginLinkLinkButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LoginLinkLinkButton.Click
Response.Redirect("/", True)
End Sub
On certain ASPX pages I would like to handle the click from the page's code behind, opposed to within the user control. How do I override the handle within the control from the parent's code behind page?
Update:
Based on the answer, I have the updated the User Control:
Public Event LoginLinkClicked As OnLoginClickHandler
Public Delegate Sub OnLoginClickHandler(ByVal sender As Object, ByVal e As EventArgs)
[...]
Private Sub LoginLinkLinkButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LoginLinkLinkButton.Click
**If OnLoginClickHandler IsNot Nothing Then**
RaiseEvent LoginLinkClicked(Me, e)
Else
Response.Redirect("/", True)
End If
End Sub
The problem is determining the correct syntax for the if line because the above is invalid.
You'll have to expose a new event from the user control. Apologies as the following code is all in C# and it's been a long time since I touched VB.Net, but you should get the idea:
You can use a delegate event by adding the following to your UserControl:
public event OnLoginClickHandler LoginClick;
public delegate void OnLoginClickHandler (object sender, EventArgs e);
Then call the following to your LinkButton Click event:
protected void LoginLinkLinkButton_Click(object sender, EventArgs e)
{
// Only fire the event if there's a subscriber
if (OnLoginClickHandler != null)
{
OnLoginClickHandler(sender, e);
}
else
{
// Not handled, so perform the standard redirect
Response.Redirect("/", true);
}
}
You can then just hook up into this within your aspx markup:
<asp:LinkButton runat="server" ID="Foo" OnLoginClick="Foo_LoginClick" />
And your server side event handler on your Page will be as follows:
protected void Foo_LoginClick_Click(object sender, EventArgs e)
{
// This event was fired from the UserControl
}
UPDATE
I think this is how you translate the event subscription check to VB.Net:
If LoginClick IsNot Nothing Then
RaiseEvent LoginClick(sender, e)
End If
I think you should have a look into below code and links.
Parent Page aspx.cs part
public partial class getproductdetails : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Button btnYes = (Button)ucPrompt.FindControl("btnYes");
btnYes.Click += new EventHandler(ucPrompt_btnYes_Click);
}
void ucPrompt_btnYes_Click(object sender, EventArgs e)
{
//Do Work
}
}
Read more details how it works (Reference) :-
Handle events of usercontrol in parent page in asp.net
Calling a method of parent page from user control

Checkbox state in itemupdating event of listview

I have a listview displaying our current projects.
In the itemediting event handler of the listview, I have a number of checkboxes that are being rendered using nested repeaters. After rendering, I loop through all checkboxes and set the correct state based on data retrieved from the DB.
The idea is that I can check or uncheck any of the checkboxes, and the changes are saved in the db.
My problem lies with the itemupdating event handler: I am unable to retain the changed checkbox states. I rebind the nested repeaters, but this seems to overwrite the checkbox states that were set during editing.
Any pointers on how to retain checkbox states generated by a repeater in the edititemtemplate of a listview would be greatly appreciated!
Thanks
Stijn
First I bind the rptDepts repeater at itemediting
Public Sub lvProjects_OnItemEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewEditEventArgs)
Dim rptDepts As Repeater = lvProjects.EditItem.FindControl("rptDepts")
rptDepts.DataSource = bllDept.getServices()
rptDepts.DataBind()
'get tasks for projectID
Dim hdnprojectID As HiddenField = lvProjects.EditItem.FindControl("hdnStudyID")
getTasks(hdnProjectID.Value, rptDepts)
End Sub
Then when rptDepts is databound, I bind the rptTasks repeater
Protected Sub lvDepts_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs)
'get tasks for service
Dim rptTasks As Repeater = e.Item.FindControl("rptTasks")
rptTasks.DataSource = bllDept.getTasksForService(e.Item.DataItem("pk_dept_id"))
rptTasks.DataBind()
End Sub
Then, at itemupdating, I rebind rptDepts (which you said I shouldn't do
Public Sub lvProjects_OnItemUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewUpdateEventArgs)
'this item
Dim itmProject As ListViewItem = lvProjects.Items(e.ItemIndex)
'rebind depts
'Dim rptDepts As Repeater = itmProject.FindControl("rptDepts")
'rptDepts.DataSource = bllDept.getServices()
'rptDepts.DataBind()
'update project
bllProject.updateProject(itmProject, lblTest)
'unset edit status
lvProjects.EditIndex = -1
'success message
pnlFeedback.CssClass = "success"
ltlFeedback.Text = "Project <b>" & txtName.Text & "</b> was successfully updated."
'rebind
bindProjects()
End Sub
But in the bllProject.updateProject method, I need to be able to reference the checkboxes to save the changes to the DB
If you rebind the nested repeaters, they will be updated from the original datasource (overwriting your changes). Try not rebinding.
Checked='<%# Eval("PreAcqClaim") ==DBNull.Value?false:true %>' MARKUP
------------------CODE BEHIND--------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Claim : System.Web.UI.Page
{
CheckBox OurFaultCheckBox = new CheckBox();
CheckBox PicturesCheckBox = new CheckBox();
CheckBox ReportedInsCheckBox = new CheckBox();
CheckBox ReportLateCheckBox = new CheckBox();
CheckBox AssistRepairCheckBox = new CheckBox();
CheckBox LitigationCheckBox = new CheckBox();
CheckBox PreAcqClaimCheckBox = new CheckBox();
DetailsDataTableAdapters.tblClaimsTableAdapter _adapter = new DetailsDataTableAdapters.tblClaimsTableAdapter();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lvDetails.DataSource = _adapter.GetDataByPK_Claim_ID(Convert.ToInt32(Request.QueryString["PK_Claim_ID"]));
lvDetails.DataBind();
}
}
protected void objDetails_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
}
protected void lvDetails_ItemDataBound(object sender, ListViewItemEventArgs e)
{
//CheckBox OurFaultCheckBox = (CheckBox)lvDetails.FindControl("OurFaultCheckBox");
//OurFaultCheckBox.Checked = true;
//OurFaultCheckBox = (CheckBox)e.Item.FindControl("OurFaultCheckBox");
//PicturesCheckBox = (CheckBox)e.Item.FindControl("PicturesCheckBox");
//ReportedInsCheckBox = (CheckBox)e.Item.FindControl("ReportedInsCheckBox");
//ReportLateCheckBox = (CheckBox)e.Item.FindControl("ReportLateCheckBox");
//AssistRepairCheckBox = (CheckBox)e.Item.FindControl("AssistRepairCheckBox");
//LitigationCheckBox = (CheckBox)e.Item.FindControl("LitigationCheckBox");
//PreAcqClaimCheckBox = (CheckBox)e.Item.FindControl("PreAcqClaimCheckBox");
}
protected void objDetails_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
CheckBox OurFaultCheckBox = (CheckBox)lvDetails.FindControl("OurFaultCheckBox");
e.InputParameters.Add("OurFaultCheckBox", OurFaultCheckBox.Checked);
}
protected void objDetails_Updating(object sender, ObjectDataSourceMethodEventArgs e)
{
e.InputParameters.Add("OurFault", OurFaultCheckBox.Checked);
e.InputParameters.Add("Pictures", PicturesCheckBox.Checked);
e.InputParameters.Add("ReportedIns", ReportedInsCheckBox.Checked);
e.InputParameters.Add("ReportLate", ReportLateCheckBox.Checked);
e.InputParameters.Add("AssistRepair", AssistRepairCheckBox.Checked);
e.InputParameters.Add("Litigation", LitigationCheckBox.Checked);
e.InputParameters.Add("PreAcqClaim", PreAcqClaimCheckBox.Checked);
}
protected void lvDetails_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
DetailsDataTableAdapters.tblClaimsTableAdapter _adapter = new DetailsDataTableAdapters.tblClaimsTableAdapter();
OurFaultCheckBox = (CheckBox)lvDetails.EditItem.FindControl("OurFaultCheckBox");
PicturesCheckBox = (CheckBox)lvDetails.EditItem.FindControl("PicturesCheckBox");
ReportedInsCheckBox = (CheckBox)lvDetails.EditItem.FindControl("ReportedInsCheckBox");
ReportLateCheckBox = (CheckBox)lvDetails.EditItem.FindControl("ReportLateCheckBox");
AssistRepairCheckBox = (CheckBox)lvDetails.EditItem.FindControl("AssistRepairCheckBox");
LitigationCheckBox = (CheckBox)lvDetails.EditItem.FindControl("LitigationCheckBox");
PreAcqClaimCheckBox = (CheckBox)lvDetails.EditItem.FindControl("PreAcqClaimCheckBox");
try
{
_adapter.Update("eventNum", "jobNum","test", "1", DateTime.Now, "", "", "",
"", "", "", DateTime.Now, "", "", "", "54143", "", "", "",
OurFaultCheckBox.Checked, PicturesCheckBox.Checked,
ReportedInsCheckBox.Checked, ReportLateCheckBox.Checked,
AssistRepairCheckBox.Checked, LitigationCheckBox.Checked,
PreAcqClaimCheckBox.Checked,
Convert.ToInt32(Request.QueryString["PK_Claim_ID"]));
}
catch (Exception ex)
{
}
lvDetails.EditIndex = -1;
}
protected void ObjectDataSource1_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
}
protected void lvDetails_ItemEditing(object sender, ListViewEditEventArgs e)
{
lvDetails.EditIndex = e.NewEditIndex;
}
}

Resources