ASP.net GridView: hide Edit|Delete links - asp.net

I have GridView with AutoGenerateDeleteButton=true && AutoGenerateEditButton=true.
I want to allow only registered users to use these functions therefore I want to hide it from unregistered users. How can I hide it?
I tried hidding the whole column but on page_load gridView is not ready yet so I get null exception.

On your pageLoad event store user Role inside Session
protected void Page_Load(object sender, EventArgs e)
{
Session["usrRole"] = "1";
}
On Row databound event of your gridview check for the session & if not equal to your administrator role, set visibility of your delete button column to false
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (Session["usrRole"] != "1")
{
e.Row.Cells[0].Visible = false; //0 is autogenerate edit column index
e.Row.Cells[1].Visible = false; // 1 is autogenerate delete column index
}
}
}

Related

Custom Cell Appearance in GridView change event

I am disabling a checkbox column in a XtraGrid GridView with the following code (works as expected). Got the code from this post https://www.devexpress.com/Support/Center/Question/Details/Q423605:
private void GridViewWeeklyPlan_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
{
if (e.Column.FieldName == "Ignore")
{
CheckEditViewInfo viewInfo = ((GridCellInfo)e.Cell).ViewInfo as CheckEditViewInfo;
viewInfo.CheckInfo.State = DevExpress.Utils.Drawing.ObjectState.Disabled;
}
}
ISSUE
I want to enable the checkbox again when a certain column changes and has a value. This is where I am stuck and I thought I can change it in the GridView's CellValueChanged event, but I do not know how to reference the cell/column for the row:
private void GridViewWeeklyPlan_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
{
if (e.Column.FieldName != "Reason") return;
if (String.IsNullOrEmpty(e.Value.ToString()))
{
//Make sure the checkbox is disabled again
}
else
{
//Enable the checkbox to allow user to select it
}
}
You need to refresh a cell in the Ignore column. You can do this by calling the GridView.RefreshRowCell method. To identify a row that you need to refresh, the CellValueChanged event provides the e.RowHandle parameter.
private void GridViewWeeklyPlan_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
{
if (e.Column.FieldName != "Reason") return;
GridView view = (GridView)sender;
view.RefreshRowCell(e.RowHandle, view.Columns["Ignore"]);
}
The CustomDrawCell event will be raised again to update the cell appearance.

Select all items in listbox when updated via UpdatePanel

protected void Page_Load(object sender, EventArgs e)
{
if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
{
string id = ScriptManager.GetCurrent(Page).AsyncPostBackSourceElementID;
if (id == cboGroup.UniqueID)
{
foreach (ListItem i in lstTest.Items)
i.Selected = true;
}
}
}
This code runs when my cboGroup causes my UpdatePanel to refresh which has the lstTest in it and the data inside of it gets updated, but it does NOT select them all. How can I make it so when my UpdatePanel is finished refreshing all elements of the list box that it refreshed get selected?
[edit] I'm noticing now that at this point what's in the listbox is the previous values and not the new values I would need. So this seems to be before the listbox is filled with data (which is via a SqlDataSource) so it's probably overwriting this.
I was able to put my selection code in the list box's DataBound() event.
protected void lstTest_DataBound(object sender, EventArgs e)
{
SelectAllTest();
}

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.

reatining selection of drodown list which is inside a user control

I have seen two few other posts related to this but I have doubts related to my code. So kindly bear with me.
I have user control which has a text boa and a drop down list and few custom validators.
The user control is added dynamically through a code.
I am using follwoing code to load the dropdownlist inside user control itself
protected void Page_Load(object sender, EventArgs e)
{
ddl_RRC.DataSource = dicRC_Desc;
ddl_RRC.DataTextField = "value";
ddl_RRC.DataValueField = "key";
ddl_RRC.DataBind();
txtRC.Text = Request.Form[txtRC.UniqueID]; //To retain the value of text box
}
I am adding the user control dynamically on Page_Init
protected void Page_Init(object sender, EventArgs e)
{
if (GetPostBackControl(this) == "btnNewRow")
{
custControlCountID++;
}
for (int i = 0; i < custControlCountID; i++)
{
RejRow customControl = (RejRow)LoadControl("~/RejRow.ascx");
customControl.ID = "rejRow" + i;
divHolder.Controls.Add(customControl);
}
}
Viewstate is enabled for both the text box and drop down list.
As I am using the same ID while adding the controls in Page_Init, why the controls are not getting the values from viewstate?
I think the only problem is that you have you're databinding the DropDownList on every postback from Page_Load. Just check the IsPostback-property, e.g.:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ddl_RRC.DataSource = dicRC_Desc;
ddl_RRC.DataTextField = "value";
ddl_RRC.DataValueField = "key";
ddl_RRC.DataBind();
}
txtRC.Text = Request.Form[txtRC.UniqueID]; //To retain the value of text box
}
However, i'm not sure why you need to set the TextBox.Text property from the form-fields since it should store it's Text also in ViewState.

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