I want display specific column in data grid view for profile of user after log in the system but my problem it is display all columns in C# with asp.net sql server, any one can help me?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.QueryString["MyID"] != null)
{
if (!IsPostBack)
{
string Id1 = Request.QueryString["MyID"];
dt = d.userunfo(Id1);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
Do you want this like?
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[index].Visible = false;
}
You can check this answer.
GridView Hide Column by code
Make sure you have specified the Datasource property of column as database column name
Add OnRowDataBound of your GridView
<asp:GridView ID="GridViewID" runat="server" OnRowDataBound="gvTest_RowDataBound" >
in RowDataBound
First, check the roles of user and then you can check the condition and hide your column
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check User Type
int userType = //Your User Type Here;
if (userType == 1)
{
GridViewID.Columns[15].Visible = false;
}
else if (userType == 2 || userType == 3)
{
GridViewID.Columns[5].Visible = false;
GridViewID.Columns[6].Visible = false;
}
}
Related
This might be a easy problem but i don't see what i'm doing wrong here. The code is:
protected void dgvSelected_RowCommand (object sender, GridViewCommandEventArgs e)
{
if(e.CommandName =="Delete")
{
if (!string.IsNullOrEmpty(e.CommandArgument.ToString()))
{
int RowIndex = Convert.ToInt32(e.CommandArgument);
dgvSelected.DeleteRow(RowIndex);
dgvSelected.DataBind();
}
}
}
And at the end of the class i have this method.
protected void dgvSelected_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
I'm using asp .net and i have a gridview that several rows and at each row i have a delete button where the user can press it to delete the row. For the moment when i press the delete button the whole gridview disappears. What am i doing wrong?
Try this
protected void dgvSelected_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
dgvSelected.DataBind();
}
Since the gridview data was from antoher gridview, the solution was to make a viewstate variable and save the datatable in it. And then to delete one row:
protected void dgvSelected_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(e.RowIndex);
DataTable dt = ViewState["SelectedValue"] as DataTable;
dt.Rows[index].Delete();
ViewState["SelectedValue"] = dt;
dgvSelected.DataSource = dt;
dgvSelected.DataBind();
}
I have listed employee names in one Dropdownlist. And by selecting any employee i am displaying employee details in gridview from database.
By default, dropdownlist have first item as selected item.So when i select another items it returns the first index only.
My Code:
protected void FilterBtn_Click(object sender, EventArgs e)
{
if (EmployeeList.SelectedIndex > -1)
{
sInitQuery = sInitQuery + " WHERE (EmployeeName ='" + EmployeeList.SelectedItem.ToString() + "')";
}
if (GlobalCS.OpenConnection() == true)
{
GridView1.DataSource = null;
GridView1.DataBind();
MySqlCommand cmd = new MySqlCommand(sInitQuery, GlobalCS.objMyCon);
MySqlDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
reader.Close();
}
GlobalCS.CloseConnection();
EmployeeList.ClearSelection();
}
Put your page load code in if condition so it is just executed first time when page is loaded, other wise whenever post back happens page load gets called and your code will get executed which is the reason it gets set to first item everytime:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
DisplayDatainGrid(); //All data in GridView
AddDataDropList(); //Load data in Dropdownlist
}
}
Currently every time your pageload code is exxecuting which should not happen.
Add EmployeeList.SelectedIndex to the ViewState.
protected void EmployeeList_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState.Add("employeeListIndex", EmployeeList.SelectedIndex);
}
Then, in Page_Load, read the ViewState and assign the value to EmployeeList.SelectedIndex.
void Page_Load(object sender, EventArgs e)
{
if(ViewState["employeeListIndex"] != null)
{
EmployeeList.SelectedIndex = ViewState["employeeListIndex"];
{
}
I have call one label inside gridview and want to assign the value for that label from code behind but couldnot being able to do that.I have created rowbound of that gridview like this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Label lbltotal= e.Row.FindControl("lbltotal");
String price=Session["price"].ToString();
DataTable dt = GridView1.DataSource as DataTable;
lbltotal.Text = dt.Compute("sum(price)", "").ToString();
}
And I am getting error like this:
(Cannot implicitly convert type 'System.Web.UI.Control' to 'System.Web.UI.WebControls.Label'. An explicit conversion exists (are
you missing a cast?))
e.Row.FindControl returns System.Web.UI.Control and this needs to be cast to the Label control explicitly
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Label lbltotal= e.Row.FindControl("lbltotal") as Label;
if(lbltotal != null)
{
String price=Session["price"].ToString();
DataTable dt = GridView1.DataSource as DataTable;
lbltotal.Text = dt.Compute("sum(price)", "").ToString();
}
}
Add an explicit conversion to it
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Label lbltotal= e.Row.FindControl("lbltotal") as Label; //explicit convert to label
if(lbltotal != null)
{
String price=Session["price"].ToString();
DataTable dt = GridView1.DataSource as DataTable;
lbltotal.Text = dt.Compute("sum(price)", "").ToString();
}
}
Please change the 1st line inside method definition as below:
Label lbltotal= e.Row.FindControl("lbltotal") as Label;
you can do as :
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbltotal=(Label) e.Row.FindControl("lbltotal");
String price=Session["price"].ToString();
DataTable dt = GridView1.DataSource as DataTable;
lbltotal.Text = dt.Compute("sum(price)", "").ToString();
}
}
Since you are looking for a Label you need to cast the Control returned from FindControl to it. You should also check if the row is a DataControlRowType.DataRow, otherwise you are also looking for the label in the header and footer.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbltotal= (Label)e.Row.FindControl("lbltotal");
var allRows = ((DataRowView)e.Row.DataItem).Row.Table.AsEnumerable();
decimal totalPrice = allRows.Sum(r => r.Field<decimal>("Price"));
lbltotal.Text = totalPrice.ToString();
}
}
//Sort User Table
private void SortGridView(string sortExpression, string direction)
{
DataTable dataTable = BindGridView(Session["useremail"].ToString()).Tables[0];
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = sortExpression + direction;
UserTable.DataSource = dataView;
UserTable.DataBind();
}
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, " ASC");
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, " DESC");
}
}
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
When I Edit a user and update the edit or do some search, and clear the search the page loads and the sort is lost,
private DataSet BindGridView(string email)
{
.......
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
.....
BindGridView(Session["useremail"].ToString());
}
everytime the page loads or some postback is done the sort is lost how to retain the sort.
Page load
if (PermissionList.Any(item => item.Equals("Edit user")))
{
if (!IsPostBack)
{
BindGridView(Session["useremail"].ToString());
}
}
Whenever you perform a new sort on your gridview, store the sort expression in a hidden label, or field, and anytime you re-load/bind your gridview, use your saved sort expression to re-sort the table.
.aspx
<asp:Label id="lblHidSortExp" runat="server" visible="false"></asp:Label>
.aspx.cs
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = lblHidSortExp.Text;
if(sortExpression == e.SortExpression)
sortExpression += " DESC";
else
sortExpression == e.SortExpression;
//not sure if this is exactly how you get your datatable, but you get the idea
DataView myView = new DataView(BindGridView(Session["useremail"].ToString()).Tables[0]);
myView.Sort = sortExpression;
marksGridView.DataSource = myView;
marksGridView.DataBind();
//save sort state
lblHidSortExp.Text = sortExpression;
}
So say in your update function, use your saved sort exp
protected void btnUpdate_Click(object sender, EventArgs e)
{
.....//do update in db
//reload your table in dataview
DataView myView = new DataView(/*load table*/);
//do sort
myView.Sort = lblHidSortExp.Text;
//bind gridview
marksGridView.DataSource = myView;
marksGridView.DataBind();
}
I had a similar problem, the way I aproached this was to save the sort values in the session, then just reset them in Page_load after they are lost.
OK So I have a web app with a dropdown field, a show button and a gridview that i can edit. Page loads, I choose my dropdown value, page loads fine. When I go to click the edit button however, I have to click it twice in order to be able to edit or cancel (having issues with that also but thats a different issue)
Anyway, I want to be able to have one click on edit to bring up the update/cancel editmode. I'm new to C# Web apps so some insight would be helpful.
Thanks
My ASP
<asp:GridView ID="GridView1" runat="server" CssClass="styled"
OnRowEditing="TaskGridView_RowEditing"
OnRowCancelingEdit="TaskGridView_RowCancelingEdit"
OnRowUpdating="TaskGridView_RowUpdating" >
<Columns>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
My C#
protected void TaskGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
//Set the edit index.
GridView1.EditIndex = e.NewEditIndex;
//Bind data to the GridView control.
// BindData();
}
protected void TaskGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
//Reset the edit index.
GridView1.EditIndex = -1;
//Bind data to the GridView control.
BindData();
Image1.Visible = true;
Image2.Visible = false;
}
protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Retrieve the table from the session object.
System.Data.DataTable dt = (System.Data.DataTable)Session["EditDataPage"];
//Update the values.
GridViewRow row = GridView1.Rows[e.RowIndex];
// dt.Rows[row.DataItemIndex]["QuoteNumber"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
// dt.Rows[row.DataItemIndex]["ItemNumber"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
//dt.Rows[row.DataItemIndex]["IsComplete"] = ((CheckBox)(row.Cells[3].Controls[0])).Checked;
// dt.Rows[row.DataItemIndex]["Item"] = ((TextBox)(row.Cells[3].Controls[0])).Text;
// dt.Rows[row.DataItemIndex]["Descp"] = ((TextBox)(row.Cells[4].Controls[0])).Text;
// dt.Rows[row.DataItemIndex]["Route"] = ((TextBox)(row.Cells[5].Controls[0])).Text;
// dt.Rows[row.DataItemIndex]["Unit"] = ((TextBox)(row.Cells[6].Controls[0])).Text;
// dt.Rows[row.DataItemIndex]["IG"] = ((TextBox)(row.Cells[7].Controls[0])).Text;
// dt.Rows[row.DataItemIndex]["EXTQTY"] = ((TextBox)(row.Cells[8].Controls[0])).Text;
// dt.Rows[row.DataItemIndex]["CSTCD"] = ((TextBox)(row.Cells[9].Controls[0])).Text;
// dt.Rows[row.DataItemIndex]["PCOST"] = ((TextBox)(row.Cells[10].Controls[0])).Text;
// dt.Rows[row.DataItemIndex]["SCOST"] = ((TextBox)(row.Cells[11].Controls[0])).Text;
// dt.Rows[row.DataItemIndex]["ACOST"] = ((TextBox)(row.Cells[12].Controls[0])).Text;
// dt.Rows[row.DataItemIndex]["TCOST"] = ((TextBox)(row.Cells[13].Controls[0])).Text;
// dt.Rows[row.DataItemIndex]["ICOST"] = ((TextBox)(row.Cells[14].Controls[0])).Text;
// dt.Rows[row.DataItemIndex]["BIZCODE"] = ((TextBox)(row.Cells[16].Controls[0])).Text;
// dt.Rows[row.DataItemIndex]["DeleteItem"] = ((TextBox)(row.Cells[17].Controls[0])).Text;
//Reset the edit index.
GridView1.EditIndex = -1;
//Bind data to the GridView control.
BindData();
}
private void BindData()
{
GridView1.DataSource = Session["Sqldatasource1"];
GridView1.DataBind();
in the rowediting event you do need to set editindex and then databind. you need to do it in the other events too. see http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowediting.aspx
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
your control may disappear if you databind unnecessarily. make sure you only databind in page_load once.
if(!Page.IsPostBack)
GridView1.DataBind();
My fix for having to click edit twice included ViewState.
My original Load and bind:
AttribGrid.DataSource = dataset;
AttribGrid.DataBind();
ViewState["CurTable"] = dataset;
then my subsequent RowEditing.
protected void AttribGrid_RowEditing(object sender, GridViewEditEventArgs e)
{
AttribGrid.EditIndex = e.NewEditIndex;
AttribGrid.DataSource = (DataSet)ViewState["CurTable"];
AttribGrid.DataBind();
}
I did have to use EditIndex = newEditIndex. When I excluded it I still had to click twice. with the above code it was click once as expected.
You do not need to set the "GridView1.EditIndex" in the Editing or Canceling callback.
protected void My_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
// Perform a custom action in here
// But you don't need to set GridView1.EditIndex in here, that would be bad.
}