How to Reload the page after Datalist Databind - c#

Asp.net with c#
i am using 16 datalist asp.net controls in my page I have programatically defined each updated command as below:
protected void DataList1_UpdateCommand(object source,
DataListCommandEventArgs e)
{
//This codes repeats for all 16 datalist , diferent naming controls such as DataList2, Datalist3, etc.....
String categoryID = DataList1.DataKeys[e.Item.ItemIndex].ToString();
String dp_status = ((DropDownList)e.Item.FindControl("DropDownList1")).SelectedValue;
//String txt_dept =
SqlDataSource1.UpdateParameters["Id"].DefaultValue = categoryID;
SqlDataSource1.UpdateParameters["Status"].DefaultValue = dp_status;
// SqlDataSource1.UpdateParameters["Comment"].DefaultValue = ;
// SqlDataSource1.UpdateParameters["Census"].DefaultValue = ;
SqlDataSource1.Update();
DataList1.EditItemIndex = -1;
DataList1.DataBind();
}
protected void DataList_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
DataRowView drv = (DataRowView)(e.Item.DataItem);
string status = drv.Row["Status"].ToString();
if (status == "Available")
e.Item.BackColor = System.Drawing.Color.LightGreen;
if (status == "Assigned")
e.Item.BackColor = System.Drawing.Color.LightSteelBlue;
if (status == "BR")
e.Item.BackColor = System.Drawing.Color.LightSalmon;
}
}//End Nt1 Change Colors
The problem is that once I update a datalist I loose the color change in my other Datalist controls....
Is there any way I can have all datalist rebind? or page reload after updating a record in any datalist?
If i insert new row / update exciting row, delete a row means automatically the gridview have to refresh. what i have to do//?....

During a postback the ItemDataBound event does not re-fire if .DataBind() is not being called. When your items are loaded from viewstate/controlstate no ItemDataBound results in no coloration.
At first cut I would remove your Item_DataBound as you have it and create a routine that iterates through each of the lists and sets the desired color. I would invoke this on pre-render.
Another choice would be to use jquery/javascript on the client once the page is loaded to do basically the same thing using styles and css.
You might get the result you want wrapping each list in an ajax 'update panel' but that will bloat your page and cost you on performance.

You can put that DataList section of your page inside an update panel like:
<asp:ScriptManager runat="server"/>
<asp:UpdatePanel runat="server">
<contentTemplate>
<!-- Your content Here -->
</contentTemplate>
</asp:UpdatePanel>
This should definitely solve your problem.

Related

How to add css class to 'hyperlink' inside 'Repeater control' from code behind based on data row counting

I am using HyperLink inside the repeater control for showing categories and counting data rows, i want to add css class based on data row counting from code behind.
like this:
if (dt.Rows.Count > 10)
{
//add css class to 'HyperLink9' that is being used inside the repeater control
}
asp.net code
<asp:Repeater ID="CloudTags" runat="server">
<ItemTemplate>
<asp:HyperLink ID="HyperLink9" runat="server">
<%#DataBinder.Eval(Container,"DataItem.Category")%>
(<%#DataBinder.Eval(Container,"DataItem.cnt")%>)
</asp:HyperLink>
</ItemTemplate>
</asp:Repeater>
code behind
protected void BindRepeaterData()
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT id, category, ( SELECT COUNT(id) FROM entry_table WHERE category.id = entry_table.cat_id) as cnt FROM category", con);
DataTable dt = new DataTable();
da.Fill(dt);
CloudTags.DataSource = dt;
if (dt.Rows.Count > 10)
{
//i want to add css class here if row count is greater than 10 in 'HyperLink9'
}
CloudTags.DataBind();
con.Close();
}
on page load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindRepeaterData();
}
}
What you'll want to do is add the ItemDataBound handler to your repeater.
<asp:Repeater ID="CloudTags" runat="server"
OnItemDataBound="CloudTags_ItemDataBound">
This event will fire each time an item is bound to the repeater. Then, during the event, check the count of the items in the repeater. Note that the count of the items will be the count of the items already bound. Since you are currently in the process of binding an item, the count will be one less than you may think. If the count is greater than or equal to 10, find the hyperlink within that RepeaterItem and add the CssClass.
protected void CloudTags_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
if (CloudTags.Items.Count >= 10)
{
HyperLink HyperLink9 = (HyperLink)e.Item.FindControl("HyperLink9");
HyperLink9.CssClass = "some-class";
}
}
}

ASP TextBox extra values after postback

In summary: I'm saving grid id and row number to some hidden textboxes inside a GridView so I can update the session data via jQuery. After a drag and drop operation on the GridView, one of the textboxes holds different data than it should. Does anyone know why this might be?
Edit: solved by doing the databinding in Page_PreRender instead of Page_Load.
I'm trying to build a page with 2 draggable and sortable GridViews. This is a 'teach myself jQuery in preparation for using those methods on production pages' kind of project. When a row is dragged and dropped, it calls a postback to update the underlying datasets and rebind the grids. Users should be able to reorder the gridviews and also drag rows from one to the other. I get the feeling that I'm making it way harder than it should be, but that's not my question.
To make the postbacks work, I'm creating 2 hidden textboxes that store the grid id and row number on each row. jQuery uses those as parameters to pass to the code-behind via a PageMethods call. All of that works, the first time.
If I try to do a drag-and-drop on a row I already dragged and dropped once, the row number textbox.text field becomes x,x instead of x like the other rows. For instance, dragging row 1 somewhere makes row 1's TextBox.Text become 1,1. I've verified that in RowDataBound the number is 1 and at Page_Unload it's 1,1. Why is this?
Javascript:
<script type="text/javascript">
$(document).ready(function () {
$( ".draggable" ).draggable({
helper: "clone",
stack: ".draggable",
snapto: ".droppable",
create: function(event, ui){
var GridID = $(this).find(".gridid").attr("value");
$(this).data("source",GridID);
var RowID = $(this).find(".rowindex").attr("value");
$(this).data("rowid",RowID);
}
});
$( ".droppable" ).droppable({
tolerance: "intersect",
greedy: true,
create: function(event, ui){
var GridID = $(this).find(".gridid").attr("value");
$(this).data("source",GridID);
var RowID = $(this).find(".rowindex").attr("value");
$(this).data("rowid",RowID);
},
drop: function(event, ui){
var SourceGrid = ui.draggable.data("source");
var SourceRow = ui.draggable.data("rowid");
var DestGrid = $(this).data("source");
var DestRow = $(this).data("rowid");
PageMethods.MoveRow(SourceGrid, DestGrid, SourceRow, DestRow);
__doPostBack('','');
}
});
});
</script>
ASP:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolderMain" runat="Server">
<asp:GridView ID="gvSource" runat="server" ShowFooter="true"
OnRowDataBound="gvSource_RowDataBound">
</asp:GridView>
<asp:GridView ID="gvDest" runat="server" ShowFooter="true"
OnRowDataBound="gvSource_RowDataBound">
</asp:GridView>
Code-Behind (minus the DataBinding and fetching parts):
protected void gvSource_RowDataBound(object sender, GridViewRowEventArgs e) {
TextBox gridid = new TextBox();
gridid.Text = ((GridView)sender).ClientID;
gridid.CssClass = "gridid hidden";
TextBox rowindex = new TextBox();
switch (e.Row.RowType) {
case DataControlRowType.DataRow:
rowindex.Text = e.Row.RowIndex.ToString();
break;
case DataControlRowType.Header:
rowindex.Text = "0";
break;
case DataControlRowType.Footer:
rowindex.Text = ((DataTable)((GridView)sender).DataSource).Rows.Count.ToString();
break;
default:
rowindex.Text = "null";
break;
}
rowindex.CssClass = "rowindex hidden";
e.Row.Cells[0].Controls.Add(gridid);
e.Row.Cells[0].Controls.Add(rowindex);
}
[WebMethod]
public static string MoveRow(string _sourcegrid, string _destgrid, string _sourcerow, string _destrow) {
HttpContext ctx = HttpContext.Current;
DataTable dtsrc = _sourcegrid == ((DataTable)ctx.Session["dtFrom"]).TableName ? (DataTable)ctx.Session["dtFrom"] : (DataTable)ctx.Session["dtTo"];
DataTable dtdest = _destgrid == ((DataTable)ctx.Session["dtFrom"]).TableName ? (DataTable)ctx.Session["dtFrom"] : (DataTable)ctx.Session["dtTo"];
DataRow row = dtsrc.Rows[Convert.ToInt32(_sourcerow)];
DataRow newrow = dtdest.NewRow();
int newrowpos = Convert.ToInt32(_destrow);
newrow.ItemArray = row.ItemArray;
dtsrc.Rows.Remove(row);
dtdest.Rows.InsertAt(newrow, newrowpos);
return "1";
}
CSS-wise, all rows have CssClass="droppable draggable". Headers and footers are just droppable. I left off some error checking code for brevity.
edit: added a summary, and I wanted to add that I've looked through SO and found only topics about a TextBox losing its data, not changing it.
The problem had something to do with binding the data in Page_Load. It looked like
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
GetData(); //Database fetch saves 2 DataTables to session variables
}
gvSource.DataSource = (DataTable)Session["dtFrom"];
gvSource.DataBind();
gvDest.DataSource = (DataTable)Session["dtTo"];
gvDest.DataBind();
}
and it failed. Made it
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
GetData(); //Database fetch
}
}
protected void Page_PreRender(object sender, EventArgs e) {
gvSource.DataSource = (DataTable)Session["dtFrom"];
gvSource.DataBind();
gvDest.DataSource = (DataTable)Session["dtTo"];
gvDest.DataBind();
}
and it worked. Why it worked is still open for debate. Thanks guys for helping this long-time lurker with basic SO usage and etiquette.

Hide DataList row based on value from web service

I am retrieving a set of value from a web service and populating a dataList with those values-
ActiveDataList.DataSource = ws.TermsReturnActive(sql);
ActiveDataList.DataBind();
How can I hide a particular column of the dataList depending on the value,
e.g.
if(value == 1)
{
//Hide Column
}
This action however would have to hide the same row of another dataList in parallel to it.
I can modify a cell on this second dataList using by retrieving the value from the first as so -
TextBox tb1 = (TextBox)sender;
DataListItem item1 = (DataListItem)tb1.NamingContainer;
TextBox txt1 = (TextBox)tData.Items[item1.ItemIndex].FindControl("tTextBox");
string term = txt1.Text;
So if I can retrieve a value from a separate dataList row, I was thinking I would also be able to adjust its visability.
How can I achieve this as the web service call is done in the page load so I believe it would have to be done when the dataList item is bound?
if iam right, you should have something like this in your aspx-file right?:
<asp:DataList ID="DataList1" runat="server" OnItemDataBound="DataList1_ItemDataBound"></asp:DataList>
As you can see you should add a "OnItemDataBound" Event where you can check your value and hide a item, if you want.
So you can react like this and hide some items:
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item)
{
TextBox tbCurrentTextBox = (TextBox)e.Item.FindControl("tTextBox");
if (DataList1.Items[e.Item.ItemIndex].ToString() == "1")
{
e.Item.Visible = false;
}
}
}

Asp.net Gridview - Why Are DataRowBound changes Lost on sort?

I am making conditional formatting changes to the data in my gridview using a RowDataBound event:
void gvReg_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DateTime lastUpdate DateTime.Parse(DataBinder.Eval (e.Row.DataItem, "LAST_UPDATE");
if (lastUpdate < DateTime.Today.AddMonths(-1))
{
Hyperlink hypLastUpdate = (Hyperlink)e.Row.FindControl("hypLastUpdate";
hypLastUpdate.CssClass = "Error";
hypLastUpdate.NavigateUrl = "http://www.someExampleErrorPage.com";
}
}
}
This works, and sets the proper CssClass to the hyperlink (which makes it a jarring shade of bold red), but once the gridview is sorted (via the user clicking a column heading) the css class is reset on hypLastUpdate and it loses both it's style and associated NavigateUrl property.
The control hypLastUpdate is contained in a template field in a gridview, and it's text value is databound to a field called "LAST_UPDATE".
Is this a planned behavior (is sorting supposed to break the conditional formatting done in RowDataBound events?) or is there something I can check to make sure I am not doing something incorrectly?
I am not using the DataBind method anywhere in the code behind, and viewstate is turned on for the gridview in question.
--EDIT--
It ended up being a mistake in event handling.
I was doing:
gvReg.Sorted += {SomeEventHandler}
Inside of the page load event, but only when it wasn't a postback. This function called gvReg.DataBind after the grid view was sorted. I removed the handler wire up and instead added the event handler function to the OnSorted event. I guess assigned delegates to a gridview are not saved in ViewState between callbacks?
Hi here is a quick example of what I meant on my comment. This is the only way i could think of it:
protected void gvReg_Sorting(object sender, GridViewSortEventArgs e)
{
GridView gridView = (GridView)sender;
if (e.SortExpression.Length > 0)
{
foreach (DataControlField field in gridView.Columns)
{
if (field.SortExpression == e.SortExpression)
{
cellIndex = gridView.Columns.IndexOf(field);
break;
}
}
if (pSortExpression != e.SortExpression)
{
pSortDirection = SortDirection.Ascending;
}
else
{
pSortDirection = (pSortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending);
}
pSortExpression = e.SortExpression;
}
//Retrieve the table from the database
pSortOrder = pSortDirection == SortDirection.Ascending ? "ASC" : "DESC";
List<Partners> partnerList = GetPartnerList();
gvReg.DataSource = partnerList;
gvReg.DataBind();
}

ASP.NET GridView EditTemplate and find control

In the GridView we are using an edit button. Once the edit button is clicked Controls in the edit template will display in the same row with update button. That row has two dropdownlist controls.
Process flow:
controls:d1 and d2
d1 is using sqldatasource for item display : working fine.
d2 is using codebehind code to load the item based on the selected value in the d1 : Not working
How to find the control in the edit template to display item value for d2?
I got the answer.
protected void GridView1_PreRender(object sender, EventArgs e)
{
if (this.GridView1.EditIndex != -1)
{
Button b = GridView1.Rows[GridView1.EditIndex].FindControl("Button1") as Button;
if (b != null)
{
//do something
}
}
}
When you switch to the edit mode, you need to rebind the grid for this to take effect.
So, you can use the 'RowDataBound' event.
void MyGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow
&& e.Row.RowIndex == MyGridView.EditIndex)
{
DropDownList d1 = e.Row.FindControl("d1") as DropDownList;
if(d1 == null) return;
//Now you have the drop down. Use it as you wish.
}
}

Categories

Resources