How to force RadGrid to postback when inner grid expand - asp.net

I have a hierarchical RadGrid and I wrote the following code that works when I select a row because I set EnablePostBackOnRowClick="true" but I want to when I expand the subgrid, it fill but now I had to select the row to bind detail grid.
protected void RadGrid1_DetailTableDataBind(object source, Telerik.Web.UI.GridDetailTableDataBindEventArgs e)
{
//e.DetailTableView.Items[e.DetailTableView.ParentItem.ItemIndex]["ID_"].Text
try
{
if (x != "0")
{
x = RadGrid1.Items[RadGrid1.SelectedIndexes[0]]["ID_"].Text.ToString();
}
GridDataItem dataItem = (GridDataItem)e.DetailTableView.ParentItem;
// Label2.Text = e.DetailTableView.Items[0]["ControlName"].Text.ToString();
e.DetailTableView.DataSource = GetDataTable("[Prg].[S_ControlList_Select]", x);
}
}

In order to have your page fire a postback when you expand the subgrid, just set the following:
In your RadGrid's definition, add the OnItemCommand setting and the ClientSettings section:
<telerik:RadGrid ID="RadGrid1" OnItemCommand="RadGrid1_ItemCommand"
<ClientSettings AllowExpandCollapse="true">
In the code behind, handle the postback:
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
switch (e.CommandName)
{
case "ExpandCollapse":
// Do something...
break;
}
}

Related

Disable GridViewColoum on Page_Load

I have a Delete-Button in my gridview that i used to create with an TemplateField + LinkButton + OnRowCommand.
Now a normal user should not be able to use this button - or better not to see this button at all.
How to disable a coloumn in a gridView on the page Log event?
Try this:
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// get the column here and your condition to make that disabled
e.Row.Cells[index].Visible = false;
}
}
You can also hide like:
((DataControlField)gridView.Columns
.Cast<DataControlField>()
.Where(fld => (fld.HeaderText == "Title"))
.SingleOrDefault()).Visible = false;
Use this: column visible use before bind grid otherwise error occurring.
protected void Page_Load(object sender, EventArgs e)
{
gridView.DataSource = "yourDatasource";
gridView.DataBind();
gridView.Columns[ColumnIndex].Visible =false;
}
Try this
In your Page_Load
GridView1.Columns[0].Visible = false;
then column 0 of the grid become disable and the other column of the grid resize automatically.

Dropdownlist in gridview not firing selectedindex changed event

I have problem with not firing selected index changed event of dropdownlist in gridview. I gone through the SO Thread . It is not worked wholly for me. I have implementation like below.
.ASPX
<asp:DropDownList ID="DDL1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DDL1_SelectedIndexChanged">
<asp:ListItem Text="Review" Value="Review" Selected="True">Review</asp:ListItem>
<asp:ListItem Text="Level1" Value="lvl1">Send Back to Level1</asp:ListItem>
</asp:DropDownList>
.CS
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// Bind the GridView to something.
DataBindGrid();
}
else {
// Bind the GridView again to maintain previous entered data in the gridview
DataBindGrid();
}
}
protected void DDL1_SelectedIndexChanged(object sender, EventArgs e)
{
this.lblCity.Text = ((DropDownList)sender).SelectedValue;
}
protected void grdPoll_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(Page.IsPostBack)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = e.Row.FindControl("DDL1") as DropDownList;
if(ddl != null)
{
ddl.SelectedIndexChanged += new EventHandler(DDL1_SelectedIndexChanged);
}
}
}
}
When i keep if(!Page.IsPostBack) block only then it works fine. But i want else block also. Whats going wrong with implentation. Can you please suggest the solutions
The problem is block after !Page.IsPostBack block, which is not event else part as you said. You are binding grid again on post back which results in loss of the event being fired. You do not have to bind it again to have the changes in the grid.
Remove this code.
{
// Bind the GridView again to maintain previous entered data in the gridview
DataBindGrid();
}
Try this:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// Bind the GridView to something.
DataBindGrid();
}
else {
// Bind the GridView again to maintain previous entered data in the gridview
//DataBindGrid(); //remove DataBindGrid(); from else
}
}
protected void DDL1_SelectedIndexChanged(object sender, EventArgs e)
{
this.lblCity.Text = ((DropDownList)sender).SelectedValue;
DataBindGrid();
}
replace event name "Page_Load" with "Page_PreRender"

Preserving user control on autopostback asp.net

I have two user controls: dsucTopLeft and dsucTopRight in an aspx page. Each of the user controls has a dropdownlist to select values from.
The aspx page has a button "Save".
In the OnClickEvent of the button, I take data from those user controls (which return the values from the drop down list). I need to insert these values into database. However, these values set to 0 after the button is clicked.
How would I preserve those values?
Code:
ParentTemplate.aspx
<div class="leftDashboard">
<uc:dsuc ID="dsucTopLeft" runat="server" />
</div>
<div id="rightDashboard">
<uc:dsuc ID="dsucTopRight" runat="server" />
</div>
It also has a button:
<asp:Button ID="SaveButton" runat="server" OnClick="SaveButton_Click" Text="Save Dashboard" />
This is the codebehind for the button:
protected void SaveButton_Click(object sender, EventArgs e)
{
//If the mode is "CREATE", then it needs to insert the information about dashboard and the charts it contains
for (int i = 0; i < dsuc.Length; i++)
{
dsuc[i].dashboardId = dashboardId;
if (dsuc[i].chartId != 0) //Here, the chartId remains 0
dsuc[i].insert();
}
}
dsuc is an array. It is being populated in the following way:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dsuc[0]=dsucTopLeft;
dsuc[1]=dsucTopRight;
}
}
UserControl:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
initializeDropDownList();//It initializes the drop down list
}
}
public void insert()
{
//It inserts into database
}
protected void chartDDLSelectedIndexChanged(object sender, EventArgs e)
{
oldChartId = chartId;
String chartTitle = chartDropDownList.SelectedItem.Text;
if (chartTitle != dropDownMessage)
{
chartId = int.Parse(chartDropDownList.SelectedItem.Value);
//Chart user control should be retrieved from the database and drawn.
chartTitleLabel.Text += "chart id : " + chartId.ToString() + " title: " + chartTitle;
//chartUserControl.Visible = true;
}
}
The user control i.e. the class of dsuc[] changes its chartId when an item in its drop down list is selected. I printed the value, it works. But that same value becomes 0 when the button in clicked.
Remove the if (!Page.IsPostBack)from
if (!Page.IsPostBack)
{
dsuc[0]=dsucTopLeft;
dsuc[1]=dsucTopRight;
}
If not, it will only populate it when is not post back. As a click produces a post back, you'll want that code being executed :)
Also, it is probably that your clickp event is being called beforeselectedindexchanged`. In that case, the code that sets chartId is not executed (yet) when the click event is fired. You can solve that doing this:
public int ChartId { get { return int.Parse(chartDropDownList.SelectedItem.Value); }}
and calling that property instead. Also, you can use that property in your selectedindexchanged event handler

Unable to FindControl() in ListView ItemEditing

I have a ListView in an ASP.NET web application. When a user clicks the edit button, I want textfields to pop up that are dependent on certain values of the item. However, I can't seem to find any controls inside of my ListView1_ItemEditing() function.
I have read the Microsoft documentation and various help threads on the internet, but their suggestions do not appear to work for me. This is generally what I see:
ListViewItem item = ProductsListView.Items[e.NewEditIndex];
Label dateLabel = (Label)item.FindControl("DiscontinuedDateLabel");
For the sake of simplicity I just want to be able to select a label in ListView1_ItemEditing(). This is the code in ListView1_ItemEditing():
protected void ListView1_ItemEditing(Object sender, ListViewEditEventArgs e)
{
DataBind(); //not sure if this does anything
ListViewItem item = ListView1.Items[e.NewEditIndex];
Label debugLabel = (Label)item.FindControl("label_editing");
debugLabel.Text = "Works";
}
Here is the ASP
<EditItemTemplate>
<asp:Label ID="label_editing" runat="server" Text="hello world"></asp:Label>
</EditItemTemplate>
When debugging, item and debugLabel are both NULL.
UPDATE: I resolved this issue by moving my logic to ItemDataBound and then checking if my tr (containing textboxes) was in that particular data item. Code below:
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
Control tr_verizon = e.Item.FindControl("tr_verizonEdit");
Control tr_att = e.Item.FindControl("tr_attEdit");
if (tr_verizon != null)
{
//Control tb_meid = e.Item.FindControl("TextBox_Meid");
Label lbl_carrierId = (Label)e.Item.FindControl("lbl_carrierId");
if (lbl_carrierId == null)
{
Message.Text = "lbl_carrierId is null!";
}
else if (lbl_carrierId.Text.Equals(""))
{
Message.Text = "lbl_carrierId is empty!";
}
else
{
string recordId = lbl_carrierId.Text;
if (tr_verizon != null && tr_att != null)
{
if (lbl_carrierId.Text.Equals("1"))
{
tr_verizon.Visible = false;
tr_att.Visible = true;
}
else
{
tr_verizon.Visible = true;
tr_att.Visible = false;
}
}
}
}
}
}
The ItemEditing event is raised when an item's Edit button is clicked, but before the ListView item is put in edit mode. Therefore controls in EditItemTemplate are not available at this time.
More Info and example
You should do the DataBind() first, like this:
ListView1.EditIndex = e.NewEditIndex;
ListView1_BindData(); // a function that get the DataSource and then ListView1.DataBind()
// Now find the control as you did before
Have you tried casting the sender object instead of trying to access your ListViewItem by index?
protected void ListView1_ItemEditing(Object sender, ListViewEditEventArgs e)
{
var item = sender as ListViewItem;
var debugLabel = item.FindControl("label_editing") as Label;
debugLabel.Text = "Works";
}

Can't seem to capture a button click in a gridview in asp.net

I put some Image Buttons into my gridview, but I cannot capture the click event. Neither creating a click event, nor creating an OnRowCommand handler in the gridview works.
Clicking the buttons simply postbacks to the current page.
I add my buttons like this:
protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string status = DataBinder.Eval(e.Row.DataItem, "visitstatusuid").ToString();
string visitUID = DataBinder.Eval(e.Row.DataItem, "visituid").ToString();
Color backColor = Color.White;
Color foreColor = Color.Black;
ImageButton b;
switch (status)
{
case "U": // Unallocated
backColor = ColorTranslator.FromHtml("#B2A1C7");
b = new ImageButton();
b.Width = Unit.Pixel(25);
b.Height = Unit.Pixel(30);
b.AlternateText = "Book";
b.ImageUrl = "../../Images/New/booking.gif";
b.ToolTip = "Booking";
b.CommandName = "Booking";
b.CommandArgument = visitUID;
b.CausesValidation = false;
e.Row.Cells[(e.Row.Cells.Count - 3)].Controls.Add(b);
etc.
You'll need to attach the handler when the button is created:
b.Click += MyButtonClickEventHandler;
Edit:
Instead of creating the button in the OnRowDataBound handler, use OnRowCreated.
This ensures the button is recreated on postbacks.
Example:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
BindData();
}
}
protected void BindData()
{
// Do your databinding here.
}
protected void MyGridView_RowCreated(object sender, GridViewRowEventArgs e)
{
var b = new ImageButton();
b.AlternateText = "Click Me!";
// Etc.
b.Click += MyButton_Click;
// Add the button to the column you want.
}
protected void MyButton_Click(object sender, ImageClickEventArgs e)
{
// Do your thing...
}
Unless you are adding an event handler elsewhere you would need to set AutoEventWireup="true" in the page directive of your aspx file.
That being said I prefer explicitly wiring events so rather than use AutoEventWireup add this line to your OnInit method:
gridview1.RowDataBound += this.gridview1_RowDataBound;
For your approach using RowDataBound to work, you need to rebind the grid on every page load, and ensure you do it no later than OnLoad in the lifecycle, in order for the click event to be registered in time.
An alternative approach I have had success with is to create a new method for doing the DataGrid button setup, e.g.
void PerformConditionalGridFormatting()
{
foreach (GridViewRow row in gvCaseList.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
... Add your buttons to the cells here
}
}
}
Then you call the method every time you perform a manual databind, and also on every postback i.e. in your OnLoad handler do:
if (Page.IsPostBack) PerformConditionalGridFormatting();
The advantage of this approach is that you don't have to databind on every postback, which saves resources.
create a RowCommand event handler for the gridview and check the command name to see if it's your button triggering it
something to the effect of
void gridview1_RowCommand(object sender, args e)
{
if (e.CommandName == "Booking")
{
// call your desired method here
}
}
Put the binding event of grid in to not post back.

Resources