I have asp:GridView where I am using AutoGenerateEditButton="True" property to edit the grid row. Now the issue is whenever I click Edit button, the columns are populating again. For example If there 4 columns and if I click Edit than same 4 columns will reappear.
.ASPX Code:
<asp:GridView ID="grdEmpDetail" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"
OnRowEditing="grdEmpDetail_RowEditing"
OnRowCancelingEdit="grdEmpDetail_RowCancelingEdit"
OnRowUpdated="grdEmpDetail_RowUpdated"
AutoGenerateEditButton="True">
</asp:GridView>
Code Behind: To Dynamically bind data on grid
protected void Page_Load(object sender, EventArgs e)
{
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
this.grdEmpDetail.AutoGenerateColumns = false;
try
{
DataTable dt = new DataTable();
dt = objBL.OrderDetail();
foreach (var col in dt.Columns)
{
if (col.ToString() == "ID" || col.ToString() == "First Name" || col.ToString() == "Last Name" || col.ToString() == "Business Phone" || col.ToString() == "Job Title")
{
BoundField objBoundField = new BoundField();
objBoundField.DataField = col.ToString();
objBoundField.HeaderText = col.ToString();
this.grdEmpDetail.Columns.Add(objBoundField);
}
}
this.grdEmpDetail.DataSource = dt;
this.grdEmpDetail.DataBind();
}
catch
{
throw;
}
}
Handle Edit Mode:
protected void grdEmpDetail_RowEditing(object sender, GridViewEditEventArgs e)
{
this.grdEmpDetail.EditIndex = e.NewEditIndex;
this.grdEmpDetail.DataBind();
}
protected void grdEmpDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.grdEmpDetail.EditIndex = -1;
this.grdEmpDetail.DataBind();
}
OUTPUT: This is fine
ISSUE : This is where I am getting issue.
What am I missing here?
You are not checking for IsPostBack in your databinding code. As a result, each time you post to the page that code is being executed again and again. So each time you will add more columns.
Modify your handler like so:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) {
// All of your existing code goes here
}
}
Edit
It's a little more complicated than that. You DO actually need to re-bind your DataGrid to the data source when you click edit, but you just don't want to add the columns again. This requires that you break up your code some so that the code for data-binding can be re-used without being tied to the column addition.
First, let's create a method specifically for adding columns that appear on an input DataTable:
private void AddColumnsToDataGrid(DataTable dt) {
foreach (var col in dt.Columns) {
if (col.ToString() == "ID"
|| col.ToString() == "First Name"
|| col.ToString() == "Last Name"
|| col.ToString() == "Business Phone"
|| col.ToString() == "Job Title")
{
BoundField objBoundField = new BoundField();
objBoundField.DataField = col.ToString();
objBoundField.HeaderText = col.ToString();
this.grdEmpDetail.Columns.Add(objBoundField);
}
}
}
Next Create a Method for Databinding a DataTable to your grid:
private void DataBindGrid(DataTable dt) {
this.grdEmpDetail.DataSource = dt;
this.grdEmpDetail.DataBind();
}
Now that you've extracted some of that code out, you can re-use these methods where appropriate, and only add columns one time:
Page Load Handler
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) {
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
this.grdEmpDetail.AutoGenerateColumns = false;
try {
DataTable dt = objBL.OrderDetail();
AddColumnsToDataGrid(dt);
DataBindGrid(dt);
} catch {
// Side Note: If you're just re-throwing the exception
// then the try/catch block is completely useless.
throw;
}
}
}
Editing Handlers
protected void grdEmpDetail_RowEditing(object sender, GridViewEditEventArgs e)
{
this.grdEmpDetail.EditIndex = e.NewEditIndex;
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
DataBindGrid(objBL.OrderDetail());
}
protected void grdEmpDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.grdEmpDetail.EditIndex = -1;
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
DataBindGrid(objBL.OrderDetail());
}
Try:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Fill_Grid();
}
}
protected Void Fill_Grid()
{
if (grdEmpDetail.Columns.Count > 0)
{
for (int n = 0; n < grdEmpDetail.Columns.Count; n++)
{
grdEmpDetail.Columns.RemoveAt(n);
}
grdEmpDetail.DataBind();
}
this.grdEmpDetail.AutoGenerateColumns = false;
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
try
{
DataTable dt = new DataTable();
dt = objBL.OrderDetail();
foreach (var col in dt.Columns)
{
if (col.ToString() == "ID" || col.ToString() == "First Name" || col.ToString() == "Last Name" || col.ToString() == "Business Phone" || col.ToString() == "Job Title")
{
BoundField objBoundField = new BoundField();
objBoundField.DataField = col.ToString();
objBoundField.HeaderText = col.ToString();
this.grdEmpDetail.Columns.Add(objBoundField);
}
}
this.grdEmpDetail.DataSource = dt;
this.grdEmpDetail.DataBind();
}
catch (exception e1)
{
}
}
protected void grdEmpDetail_RowEditing(object sender, GridViewEditEventArgs e)
{
this.grdEmpDetail.EditIndex = e.NewEditIndex;
Fill_Grid();
}
protected void grdEmpDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.grdEmpDetail.EditIndex = -1;
Fill_Grid();
}
Related
So I have a sipme ASP.NET Web Page that prints the info of one's gender stacked dynamically in a radio button list:
protected void Page_Load(object sender, EventArgs e)
{
String[] genders = new String[2];
genders[0] = "Male";
genders[1] = "Female";
RadioButtonList1.DataSource = genders;
RadioButtonList1.DataBind();
RadioButtonList1.Items.Add(new ListItem("Neutral", "Zero"));
}
protected void Button1_Click(object sender, EventArgs e)
{
lblName.Text = txtName.Text;
lblSurname.Text = txtSurname.Text;
lblEmail.Text = txtMail.Text;
Panel1.Visible = true;
if (RadioButtonList1.SelectedIndex==0) lblGender.Text = "Male";
else lblGender.Text = "Female";
}
However when I launch the site no matter what I select it always writes female it's like the RadioButtonList1.SelectedIndex==0 isn't working.
Any ideas?
Bind radiobuttonlist in page_Load with !IsPostBack condition or your radiobuttonlist will bind every time you post your page. So your radiobuttonlist is reset to index -1 when you click the button_click.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
String[] genders = new String[2];
genders[0] = "Male";
genders[1] = "Female";
RadioButtonList1.DataSource = genders;
RadioButtonList1.DataBind();
RadioButtonList1.Items.Add(new ListItem("Neutral", "Zero"));
}
}
Not sure why but i cant get my data to return. It starts out saying there is not data records to display. But when i select the month and year of the information i am looking for the grid view disappears. Any suggestions
NutritionEntities context;
protected void Page_Load(object sender, EventArgs e)
{
context = new NutritionEntities();
if (!IsPostBack)
{
for (int i = DateTime.Now.Year; i > 1988; i--)
{
ddlYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
int selectedMonth = int.Parse(ddlMonth.SelectedValue);
int selectedYear = int.Parse(ddlYear.SelectedValue);
GridView1.DataSource =
from exercise in context.Exercises
where exercise.exerciseDate.Value.Month == selectedMonth && exercise.exerciseDate.Value.Year == selectedYear
select new
{
exercise.exerciseDate,
exercise.duration,
exercise.caloriesBurned,
exercise.averageHR,
exercise.distanceInMiles,
exercise.notes
};
GridView1.DataBind();
}
}
protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedMonth = int.Parse(ddlMonth.SelectedValue);
int selectedYear = int.Parse(ddlYear.SelectedValue);
GridView1.DataSource =
from exercise in context.Exercises
where exercise.exerciseDate.Value.Month == selectedMonth && exercise.exerciseDate.Value.Year == selectedYear
select new
{
exercise.exerciseDate,
exercise.duration,
exercise.caloriesBurned,
exercise.averageHR,
exercise.distanceInMiles,
exercise.notes
};
GridView1.DataBind();
}
protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedMonth = int.Parse(ddlMonth.SelectedValue);
int selectedYear = int.Parse(ddlYear.SelectedValue);
GridView1.DataSource =
from exercise in context.Exercises
where exercise.exerciseDate.Value.Month == selectedMonth && exercise.exerciseDate.Value.Year == selectedYear
select new
{
exercise.exerciseDate,
exercise.duration,
exercise.caloriesBurned,
exercise.averageHR,
exercise.distanceInMiles,
exercise.notes
};
GridView1.DataBind();
}
you have verify the binding of your control grid, i suggest add only object to the datasource of the grid on the pageLoad when the postback its false like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource =
from exercise in context.Exercises
where exercise.exerciseDate.Value.Month == selectedMonth && exercise.exerciseDate.Value.Year == selectedYear
select new
{
exercise.exerciseDate,
exercise.duration,
exercise.caloriesBurned,
exercise.averageHR,
exercise.distanceInMiles,
exercise.notes
};
}
GridView1.DataBind();
}
the problem is when you add the objects to datasource , when any event refresh the web page like select the control is unbinding, i hope help you,, see you!!
i am trying to hid some columns of gridView on run time by matching their HeaderText but its not working for me. here is the code i am trying
protected void gridview_rowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (DataControlField col in gvRecoed.Columns)
{
try
{
if (col.HeaderText == cat_check.SelectedItem.Text.Trim())
{
col.Visible = false;
}
}
catch (Exception exe)
{ }
}
}
cat_check is a CheckBoxList
Why do you want to hide the column in RowDataBound which is triggered for every row in the grid?
Instead you could use the DataBound event which is called once after the grid was databound.
protected void gridview_DataBound(object sender, EventArgs e)
{
if(cat_check.SelectedItem != null)
{
string columnName = SelectedItem.Text;
var column = gridView1.Columns.Cast<DataControlField>()
.FirstOrDefault(c => c.HeaderText == columnName);
if (column != null) column.Visible = false;
}
}
protected void gridview_rowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (DataControlField col in gvSource.Columns)
{
try
{
if (col.HeaderText == cat_check.SelectedItem.Text.Trim())
{
col.Visible = false;
}
}
catch (Exception exe)
{ }
}
}
}
Here is the simple answer.
Create css as below
.classHide{
display:none
}
then instead of col.hide,just assign classHide cssclass to the column.
e.g. col.cssclass="classHide"
i have a listview and a button out of this list view, on button click i want to add a "insert" row defined in InsertItemTemplate. The problem is when i click the button, this row is added(i know this because when a do any postback aftewards this row really shows), but isnt shown/rendered. So the question is: why this change doesn´t apply on the first postback - button click? here is my code:
EDIT:
Whole Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListItem ByName = new ListItem("By name", "Name");
ListItem ByPhone = new ListItem("By phone", "Phone");
ListItem ByEmail = new ListItem("By email", "Email");
FilterTypeDDL.Items.Add(ByName);
FilterTypeDDL.Items.Add(ByPhone);
FilterTypeDDL.Items.Add(ByEmail);
FilterTypeDDL.DataBind();
}
}
//protected void ListView_ItemCommand(object sender, ListViewCommandEventArgs e)
//{
//switch (e.CommandName)
//{
//case "EditItem":
// break;
//case "InsertItem":
// if (Page.IsValid)
// {
// string NameTxt = ((TextBox)(ListView.InsertItem.FindControl("NameTextBox"))).Text.Trim();
// string PhoneTxt = ((TextBox)(ListView.InsertItem.FindControl("PhoneTextBox"))).Text.Trim();
// string EmailTxt = ((TextBox)(ListView.InsertItem.FindControl("EmailTextBox"))).Text.Trim();
// DAORestaurant.InsertRestaurant(NameTxt, PhoneTxt, EmailTxt);
// ListView.InsertItemPosition = InsertItemPosition.None;
// ListView.DataSource = DAORestaurant.GetRestaurants();
// ListView.DataBind();
// break;
// }
// break;
//case "CancelCreation":
// ListView.InsertItemPosition = InsertItemPosition.None;
// ListView.DataSource = DAORestaurant.GetRestaurants();
// ListView.DataBind();
// break;
//case "Articles":
// Session["Restaurant"] = e.CommandArgument.ToString();
// Control ArticlesCtrl = LoadControl("~/Controls/Article.ascx");
// ListViewItem Item = (ListViewItem)e.Item;
// Item.FindControl("CtrlPlaceHolder").Controls.Add(ArticlesCtrl);
//}
//}
protected void closeButton_Click(object sender, EventArgs e)
{
}
protected void newArticleButton_Click(object sender, EventArgs e)
{
}
protected void NewRestaurantBtn_Click(object sender, EventArgs e)
{
ListView.InsertItemPosition = InsertItemPosition.LastItem;
//SetDataSource();
//ListView.DataBind();
}
protected void ValidateName(object source, ServerValidateEventArgs args)
{
string NameTxt = ((TextBox)(ListView.InsertItem.FindControl("NameTextBox"))).Text.Trim();
args.IsValid = (NameTxt.Length > 2 && NameTxt.Length < 51);
}
protected void ValidateUniqueness(object source, ServerValidateEventArgs args)
{
string NameTxt = ((TextBox)(ListView.InsertItem.FindControl("NameTextBox"))).Text.Trim();
args.IsValid = DAORestaurant.IsUnique(NameTxt);
}
protected void ValidatePhone(object source, ServerValidateEventArgs args)
{
string PhoneTxt = ((TextBox)(ListView.InsertItem.FindControl("PhoneTextBox"))).Text.Trim();
Regex regex = new Regex(#"^\d{3}\s\d{3}\s\d{3}$");
args.IsValid = regex.IsMatch(PhoneTxt);
}
protected void ValidateEmail(object source, ServerValidateEventArgs args)
{
string EmailTxt = ((TextBox)(ListView.InsertItem.FindControl("EmailTextBox"))).Text.Trim();
Regex regex = new Regex(#"^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$");
args.IsValid = regex.IsMatch(EmailTxt);
}
protected void ShowAllBtn_Click(object sender, EventArgs e)
{
Session["ALL"] = true;
ListView.DataSource = DAORestaurant.GetRestaurants();
ListView.DataBind();
}
protected void FilterBtn_Click(object sender, EventArgs e)
{
string filterType = FilterTypeDDL.SelectedValue;
string substring = StringTB.Text.Trim().ToUpper();
Session["ALL"] = false;
Session["FilterType"] = filterType;
Session["Substring"] = substring;
ListView.DataSource = DAORestaurant.GetRestaurants(substring, filterType);
ListView.DataBind();
}
protected void ListView_ItemEditing(object sender, ListViewEditEventArgs e)
{
ListView.EditIndex = e.NewEditIndex;
//SetDataSource();
//ListView.DataBind();
}
protected void ListView_ItemInserting(object sender, ListViewInsertEventArgs e)
{
}
protected void ListView_ItemCanceling(object sender, ListViewCancelEventArgs e)
{
if (e.CancelMode == ListViewCancelMode.CancelingInsert)
{
ListView.InsertItemPosition = InsertItemPosition.None;
}
else
{
ListView.EditIndex = -1;
}
//SetDataSource();
//ListView.DataBind();
}
private void SetDataSource()
{
if ((bool)Session["ALL"])
{
ListView.DataSource = DAORestaurant.GetRestaurants();
}
else
{
ListView.DataSource = DAORestaurant.GetRestaurants((string)Session["Substring"], (string)Session["FilterType"]);
}
}
The code commented out is what i used before, i´ve switched to what you can see now, but the problem still persists. Only when i uncomment those 2 commented lines in each event, the changes apply instantly, but i know i cannot use such a method that many times, and it should not even be there.
Because of the order of execution. Try setting it in the Page_Load event:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack &&
!string.IsNullOrEmpty(Request.Form[NewRestaurantBtn.ClientID]))
{
ListView.InsertItemPosition = InsertItemPosition.LastItem;
}
}
I am using GridView in asp.net. I want to select a single data row. I looked for MultiSelect and SelectionMode in property panel, but I can't find it.
So how to enable selecting rows in GridView?
Thanks.
Code Behind
public partial class SearchCourse : System.Web.UI.Page
{
Connection dbCon;
DataTable tbl;
protected void Page_Load(object sender, EventArgs e)
{
dbCon = new Connection();
}
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton1.Checked) {
txtSubName.Enabled = true;
comboSemester.Enabled = false;
comboYear.Enabled = false;
comboProgram.Enabled =false;
txtSubName.Text = "";
}
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton2.Checked) {
comboProgram.Enabled = true;
if (comboProgram.SelectedItem.ToString() == "Foundation Course")
{
comboSemester.Enabled = false;
comboYear.Enabled = false;
}
else {
comboSemester.Enabled = true;
comboYear.Enabled = true;
}
txtSubName.Text = "";
txtSubName.Enabled = false;
}
}
protected void imgBtnSearch_Click(object sender, ImageClickEventArgs e)
{
if (RadioButton1.Checked) {
String name = txtSubName.Text;
tbl = dbCon.getResultsBySubjectName(name);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
else if (RadioButton2.Checked)
{
String program = comboProgram.SelectedItem.ToString();
String year = comboYear.SelectedItem.ToString();
String sem= comboSemester.SelectedItem.ToString();
tbl = dbCon.getResultsByProgram(program,year,sem);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
else if (RadioButton3.Checked)
{
String name = txtSubName.Text;
tbl = dbCon.getResultsBySubjectNo(name);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
String program = comboProgram.SelectedItem.ToString();
String year, sem;
if (program == "Foundation Course")
{
comboYear.Enabled = false;
comboSemester.Enabled = false;
year = null;
sem = null;
}
else {
comboYear.Enabled = true;
comboSemester.Enabled = true;
year = comboYear.SelectedItem.ToString();
sem = comboSemester.SelectedItem.ToString();
}
tbl = dbCon.getResultsByProgram(program, year, sem);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
protected void comboYear_SelectedIndexChanged(object sender, EventArgs e)
{
String program = comboProgram.SelectedItem.ToString();
String year = comboYear.SelectedItem.ToString();
String sem = comboSemester.SelectedItem.ToString();
tbl = dbCon.getResultsByProgram(program, year, sem);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
protected void comboSemester_SelectedIndexChanged(object sender, EventArgs e)
{
String program = comboProgram.SelectedItem.ToString();
String year = comboYear.SelectedItem.ToString();
String sem = comboSemester.SelectedItem.ToString();
tbl = dbCon.getResultsByProgram(program, year, sem);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
protected void RadioButton3_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton3.Checked)
{
txtSubName.Enabled = true;
comboSemester.Enabled = false;
comboYear.Enabled = false;
comboProgram.Enabled = false;
txtSubName.Text = "";
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
GridView Code
<asp:GridView ID="GridView1" CssClass="grid" runat="server" AllowPaging="True"
BorderColor="Black" BorderStyle="Solid" BorderWidth="2px"
GridLines="Horizontal" EnableViewState="False"
PageSize="5" onselectedindexchanged="GridView1_SelectedIndexChanged" >
<RowStyle CssClass="gridRow" Width="800px" />
<SelectedRowStyle BackColor="#FF0066" ForeColor="White" />
</asp:GridView>
I think the MultiSelect and SelectionMode properties are only available with the VB.NET grid, not in ASP.NET. Bear in mind that all controls in ASP.NET are HTML-in-disguise, so they may be more limited. There is no reason why you can't have a multi-select table, but you have to do the plumbing yourself. So you need to enable row selection, either by handling the RowDataBound event as in
http://forums.asp.net/t/992062.aspx?How+to+select+row+in+gridview+on+click
or else using the MS-provided option as in
http://msdn.microsoft.com/en-us/library/wbk82279(v=vs.100).aspx
Then you need to handle the SelectedIndexChanging event, figure out which row the user clicked on, and handle the row-colouring yourself.
This problem is still actual for me 9 years later.
In As?x code I added SelectedRowStyle and asp:CommandField blocks:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<SelectedRowStyle BackColor="#337ab7" ForeColor="White" />
<Columns>
<asp:CommandField SelectText="Select" ShowSelectButton="True">
<HeaderStyle Width="50px" />
</asp:CommandField>
Code behind:
protected void GridView1_OnSelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
}
In gridview you have to define an event onselectedindexchanged and onrowdatabound as below:
onselectedindexchanged="GridView1_SelectedIndexChanged" onrowdatabound="GridView1_RowDataBound"
to show the selected row you can use following style in your grid view:
<SelectedRowStyle BackColor="Red" />
in code behind:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Set the hand mouse cursor for the selected row.
e.Row.Attributes.Add("OnMouseOver", "this.style.cursor = 'hand';");
// The seelctButton exists for ensuring the selection functionality
// and bind it with the appropriate event hanlder.
LinkButton selectButton = new LinkButton()
{
CommandName = "Select",
Text = e.Row.Cells[0].Text
};
selectButton.Font.Underline = false;
selectButton.ForeColor = Color.Black;
e.Row.Cells[0].Controls.Add(selectButton);
//e.Row.Attributes["OnClick"] =
// Page.ClientScript.GetPostBackClientHyperlink(selectButton, "");
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
}
}
note: you can find the event in event window.