RowCommand not getting fired on Dynamically created GridView - c#

I am creating a gridview dynamically with a ButtonField and several BoundFields. ButtonField button type is LinkButton. If i run it the buttonclick triggers a post back but rowCommand is not triggered. It is not triggered even if i use AutogenerateSelectButton. The event is dyanamically bound. Code As follows:
protected void B_Search_Click(object sender, EventArgs e) //Search buttonclick that creates and displays the gridview
{
gd = getGridView(); //defines the gridview with columns and buttonfield
gd.DataSource = executeAdvanceSearch(); //retrieves data from DB as Dataset
gd.DataBind();
gd.RowCommand += new GridViewCommandEventHandler(gdView_RowCommand); //Rowcommand event binding
PlaceHolder1.Controls.Add(gd);
}
protected void gdView_RowCommand(object sender, GridViewCommandEventArgs e) //not getting triggered on postback
{
int index = Convert.ToInt32(e.CommandArgument);
GridView gdView = (GridView)sender;
if (e.CommandName == "IDClick")
{
//Do something
}
}
private GridView getGridView()
{
GridView gdView = new GridView();
gdView.AutoGenerateColumns = false;
gdView.AutoGenerateSelectButton = true;
string name;
string[] field = ZGP.BLL.Search.getResultFormat(Convert.ToInt32(DDL_ResultView.SelectedValue), out name); //Ignore. This jst gets columnNames
if (field.Count() != 0)
{
gdView.Columns.Add(getSelectButton()); //Adds linkbutton
foreach (string cName in field) //ignore. This adds columns.
if (!String.IsNullOrEmpty(cName))
{
gdView.Columns.Add(GV_DataColumn.getGridViewColumn((DataColumnName)Enum.Parse(typeof(DataColumnName), cName))); //Ignore. adds columns
}
}
return gdView;
}
private ButtonField getSelectButton()
{
ButtonField _bf = new ButtonField();
_bf.ButtonType = ButtonType.Link;
_bf.HeaderText = "ID";
_bf.DataTextField = "ID";
_bf.CommandName = "IDClick";
return _bf;
}
Thanks for the help.

if (e.CommandName=="CommandName")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
string boundFieldText= row.Cells[0].Text;
}

You'll need to create the grid view on each postback.

Related

ASP.NET Textbox losing values after postback which were set during editing

There's a gridview in my program whose row's data is to be loaded in textboxes if edit is clicked.
Here is the code where I'm filling the data in textboxes after edit is clicked
protected void GV_Parameters_RowEditing(object sender, GridViewEditEventArgs e)
{
GV_Parameters.EditIndex = e.NewEditIndex;
int index = e.NewEditIndex;
IsEditing = true;
Label lbl_frmdate = (Label)GV_Parameters.Rows[index].FindControl("lbl_frmdate") as Label;
Label lbl_todate = (Label)GV_Parameters.Rows[index].FindControl("lbl_todate") as Label;
EditFromDate = lbl_frmdate.Text.ToUpper();
lbl_frm_edit.Text = EditFromDate;
EditToDate = lbl_todate.Text.ToUpper();
lbl_to_edit.Text = EditToDate;
Label lbl = (Label)GV_Parameters.Rows[index].Cells[3].FindControl("lbl_Is_holiday");
string is_holiday = lbl.Text;
Label lbl_std_intime = (Label)GV_Parameters.Rows[index].FindControl("lbl_std_intime") as Label;
Label lbl_std_outtime = (Label)GV_Parameters.Rows[index].FindControl("lbl_std_outtime") as Label;
string[] arr_std_intime;
string[] arr_std_outtime;
if (is_holiday != "1")//working day
{
r_work_holiday.SelectedIndex = 0;
IsHoliday = false;
if (lbl_std_intime.Text != "")
{
arr_std_intime = lbl_std_intime.Text.Split(':');
txt_std_TimeInHours.Text = arr_std_intime[0].ToString();
txt_std_TimeInMins.Text = arr_std_intime[1].ToString();
}
if (lbl_std_outtime.Text != "")
{
arr_std_outtime = lbl_std_outtime.Text.Split(':');
txt_std_TimeOutHours.Text = arr_std_outtime[0].ToString();
txt_std_TimeOutMins.Text = arr_std_outtime[1].ToString();
}
}
else
{
IsHoliday = true;
//r_workingday.Checked = false;
//r_holiday.Checked = true;
r_work_holiday.SelectedIndex = 1;
Label lbl_remarks = (Label)GV_Parameters.Rows[index].FindControl("lbl_remarks") as Label;
txt_holiday_desc.Text = lbl_remarks.Text;
}
collapse_state = "expand";
}
There is a radiobutton list who shows the edited row is holiday or working day,
if user changes the selection in radioButtonList, PostBack occurs and this is the time when all of the texboxes turn blank.
protected void r_work_holiday_SelectedIndexChanged(object sender, EventArgs e)
{
if(r_work_holiday.SelectedIndex==0)
{
IsHoliday = false;
}
else
{
IsHoliday = true;
}
collapse_state = "expand";
}
There's no any method in page load who is clearing the textboxes.
protected void Page_Load(object sender, EventArgs e)
{
if (IsEditing)
{
collapse_state = "expand";
}
if (!Page.IsPostBack)
{
BindYears();
}
}
Please help
Update ::
lbl_frm_edit and lbl_to_edit are not getting reset after postback.
The variable EditFromDate and EditToDate are being set by Viewstate
It's been sometime I worked in ASP controls but if I remember correctly, the content in textboxes are generally cleared on every post back by ASP .NET. The state of the textboxes are not saved.
Here is an answer I found while researching this issue.
You could store the value of the textboxes in ViewState and assign them back on the PageLoad event. Something like
txt_std_TimeOutHours.Text = arr_std_outtime[0].ToString();
txt_std_TimeOutMins.Text = arr_std_outtime[1].ToString();
ViewState["TimeOutHours"] = arr_std_outtime[0].ToString();
ViewState["TimeOutMins"] = arr_std_outtime[1].ToString();
And on the PageLoad event you can do this to restore the values.
if(Page.IsPostBack)
{
txt_std_TimeOutHours.Text = ViewState["TimeOutHours"].ToString();
txt_std_TimeOutMins.Text = ViewState["TimeOutMins"].ToString();
}
Hope this helps!

Accessing dynamically generated dropdownlist in Gridview_RowUpdating event

I am using Gridview with AutoGenerateColumns="True", so gridview columns are generated dynamically. Now in case of edit, I am adding dropdownlist dynamically for one of the field in the gridview. Please see following code:
protected void grdViewConfig_RowEditing(object sender, GridViewEditEventArgs e)
{
grdViewConfig.EditIndex = e.NewEditIndex;
BindGridView();
clientBAL = new TMIWsBALClient();
var lstAppIds = clientBAL.GetDistinctApplicationIds();
GridViewRow grdRow = grdViewConfig.Rows[e.NewEditIndex];
for (int i = 0; i < grdRow.Cells.Count; i++)
{
if (grdRow.Cells[i].GetType().Equals(typeof(DataControlFieldCell)))
{
DataControlFieldCell dcField = (DataControlFieldCell )grdRow.Cells[i];
if (dcField.ContainingField.HeaderText.ToLower().Equals("applicationid"))
{
DropDownList drpDwnAppIds = new DropDownList();
drpDwnAppIds.ID = "drpDwnAppIds";
drpDwnAppIds.DataSource = lstAppIds;
drpDwnAppIds.DataBind();
var tb = dcField.GetAllControlsOfType<TextBox>(); ;// grdRow.Cells[i].GetAllControlsOfType<TextBox>();
TextBox firstTb = (TextBox)tb.First();
foreach (ListItem lstItem in drpDwnAppIds.Items)
{
if (firstTb.Text.Equals(lstItem.Text, StringComparison.CurrentCultureIgnoreCase))
{
lstItem.Selected = true;
}
}
dcField.Controls.Remove(firstTb);
dcField.Controls.Add(drpDwnAppIds);
}
}
}
}
Now in Gridview_RowUpdating event, I am trying to fetch the dropdownlist in similar way, but I am unable to get it. GetAllControlsOfType() is an extension method, which will return all the child controls under selected parent. In this case, parent is gridview cell and child control is dropdownlist. But it is returning null.
protected void grdViewConfig_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
strTableName = txtTable.Text.Trim();
string strAppId;
GridViewRow grdRow = grdViewConfig.Rows[grdViewConfig.EditIndex];
for (int i = 0; i < grdRow.Cells.Count; i++)
{
if (grdRow.Cells[i].GetType().Equals(typeof(DataControlFieldCell)))
{
DataControlFieldCell dcField = (DataControlFieldCell)grdRow.Cells[i];
if (dcField.ContainingField.HeaderText.ToLower().Equals("applicationid"))
{
var drpDwn = dcField.GetAllControlsOfType<DropDownList>();
DropDownList drpDwnAppIds = (DropDownList)drpDwn.First();
strAppId = drpDwnAppIds.SelectedValue;
}
}
}
}
What am I missing? Please help. Also let me know if more information is needed.
Thank you in advance.
Dynamically generated controls need to be recreated on every postback. In your case the DropDownList controls you created no longer exist when you hit the grdViewConfig_RowUpdating handler.
Generally in this sort of case you would set AutoGenerateColumns to false and manually define your columns which would allow you to define a TemplateField which contains an ItemTemplate for read only mode and an EditItemTemplate for edit mode which could then contain your DropDownList.

ASP.Net Gridview not rebind data on button click

i am new in asp.net i using LINQ with asp.net on button click event my gridview not rebind data and yes gridview is into the updatepanel
'>
'>
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gvClientData.Rows)
{
if (((CheckBox)gvr.FindControl("chkdisplay")).Checked == true)
{
string Index = ((Label)gvr.FindControl("lblIndex")).Text;
int GIIndex = Convert.ToInt32(Index);
GI_InsureMaster insertclientinfo = vjdb.GI_InsureMasters.Single(upd => upd.GIMastIndex == GIIndex);
insertclientinfo.SendToCompany = true;
vjdb.SubmitChanges();
}
}
BindAgencyData();
Response.Redirect(Request.RawUrl);
}
It seems you are trying to modify an object and then saving it back to the DB, but you are doing it wrong.
You are querying the object from a different Data Context, vjdb and you are calling SubmitChanges on linqobject. You should call SubmitChanges on vjdb
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gvClientData.Rows)
{
if (((CheckBox)gvr.FindControl("chkdisplay")).Checked == true)
{
string Index = ((Label)gvr.FindControl("lblIndex")).Text;
int GIIndex = Convert.ToInt32(Index);
GI_InsureMaster insertclientinfo = vjdb.GI_InsureMasters.Single(upd => upd.GIMastIndex == GIIndex);
insertclientinfo.SendToCompany = true;
vjdb.SubmitChanges(); //HERE
}
}
BindAgencyData();
Response.Redirect(Request.RawUrl);
}
Assuming that BindAgencyData is querying database for latest/updated record and then binding the data to the grid.

Checkbox Checked Event for multiple dynamic Checkboxes

I have an aspx page where I dynamically create checkboxes and add them to a panel from data in a SQL database. I need to have only one checkbox checked at a time. I have tried and googled just about everything but I cannot get the right answer. How would I go about getting that done.
My code for creating the checkboxes
public void CreateTimeSelection()
{
DataSet times = GetTimes();
int i = 0;
foreach (DataTable table in times.Tables)
{
foreach (DataRow row in table.Rows)
{
CheckBox chkTime = new CheckBox();
i += 1;
chkTime.ID = row["Time"].ToString();
chkTime.AutoPostBack = true;
chkTime.Text = row["Time"].ToString();
chkTime.CheckedChanged += new EventHandler(this.CheckChanged_click);
pnlTimeSlots.Controls.Add(chkTime);
pnlTimeSlots.Controls.Add(new LiteralControl("<br />"));
}
}
}
Code for Checkbox event handlers
protected void CheckChanged_click(object sender, EventArgs e)
{
CheckBox chkSelect = (CheckBox)sender;
if (chkSelect.Checked == true)
{
//set other checkboxes to false
}
}

Delete link button work after page refresh in gridview

Here is my code for grid row delete using link button but after click its deleted data after page refresh I want delete data on the page without refresh the page i also put update panel in my grid here is my code
protected void gvContent_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="modify")
{
GridViewRow row =
(GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
// this find the index of row:
int RowIndex = row.RowIndex;
//this store the value in varName1:
int id = Convert.ToInt32(
((Label)row.FindControl("lblContentId")).Text.ToString());
Response.Redirect("ContentManage.aspx?ContentId=" +Convert.ToInt32(id));
}
if (e.CommandName == "delete")
{
GridViewRow row = (GridViewRow)
(((LinkButton)e.CommandSource).NamingContainer);
// this finds the index of row:
int RowIndex = row.RowIndex;
//this stores the value in varName1:
int id = Convert.ToInt32(
((Label)row.FindControl("lblContentId")).Text.ToString());
Content_Data.DeleteContentDetails(id);
BindGrid();
UpdatePanel1.Update();
}
You would need to register gvContentas an async post-back control using the followin
void Page_Load()
{
if (!IsPostBack)
{
ScriptManager1.RegisterAsyncPostBackControl(gvContent);
}
}
This will cause your Grid to do async post-backs.
Hope that helps
Try adding an empty RowDeleting event
protected void gvContent_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}

Categories