OnRowCommand="grd_RowCommand" event not firing when click on row - c#

here i bind grid columns dynamically using code behind because my GetSocailAnalytics method return dynamic column according to parameter passed.after binding column of grid using data table my grd_OnRowCommand event not firing when i click on grid row. grid is successfully bind. can any one help me out this issue.here is my code...
<asp:GridView ID="grd" EnableViewState="true" AutoGenerateColumns="false" OnRowCommand="grd_RowCommand"
runat="server" OnRowDataBound="grd_RowDataBound">
<Columns>
</Columns>
</asp:GridView>
private void GetData()
{
try
{
int TotalRecords = 0;
DataTable dt = ClsSocialManager.GetSocialAnalytics(Convert.ToInt32(hdnReferrerId.Value), Convert.ToInt32(hdnReferralId.Value), out TotalRecords, Convert.ToInt32(hdnPageIndex.Value));
if (dt != null && dt.Rows.Count > 0)
{
BindTemplateFiled(dt);
grd.Visible = true;
}
else
{
grd.Visible = false;
}
lblStatus.Text = TotalRecords.ToString() + " Record(s) found";
}
catch (Exception ex)
{
lblStatus.Text = "Some Error Occured " + ex.Message;
lblStatus.CssClass = "ErrMsg";
}
}
//Start Crearting GridColumn Dynamically
class LinkColumn : ITemplate
{
public void InstantiateIn(System.Web.UI.Control container)
{
LinkButton link = new LinkButton();
link.ID = "lnkbtnReferrerHost";
link.DataBinding += new EventHandler(this.link_DataBinding);
link.CommandName = "sad";
container.Controls.Add(link);
}
private void link_DataBinding(Object sender, EventArgs e)
{
LinkButton lnkReferrerHost = (LinkButton)sender;
GridViewRow row = (GridViewRow)lnkReferrerHost.NamingContainer;
lnkReferrerHost.Text = Convert.ToString((((System.Data.DataRowView)(row.DataItem))).Row[1]);
lnkReferrerHost.CommandArgument = Convert.ToString((((System.Data.DataRowView)(row.DataItem))).Row[0]);
//lnkReferrerHost.CommandName = "Filter";
}
}
private void BindTemplateFiled(DataTable dt)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
if (dt.Columns[i].ColumnName == "Referrer Host")
{
var lnkbtnReferrerHost = new TemplateField();
lnkbtnReferrerHost.ItemTemplate = new LinkColumn();
lnkbtnReferrerHost.HeaderText = dt.Columns[i].ColumnName;
grd.Columns.Add(lnkbtnReferrerHost);
}
else
{
BoundField field = new BoundField();
field.DataField = dt.Columns[i].ColumnName;
field.HeaderText = dt.Columns[i].ColumnName;
grd.Columns.Add(field);
}
}
grd.DataSource = dt;
grd.DataBind();
}
//End Crearting GridColumn Dynamically
protected void grd_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "Filter")
{
GridViewRow gvr = (GridViewRow)grd.Rows[((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex];
LinkButton lbtn = (LinkButton)gvr.FindControl("lnkReferrerHost");
hdnReferrerId.Value = Convert.ToString(Convert.ToInt32(e.CommandArgument));
lblCurrentPage.Text = lbtn.Text;
GetData();
}
}
catch
{
}
}

The RowCommand event is raised when a button is clicked in the
GridView control.
it is not not firing when you click on grid row
solution is adding button (LinkButton) column to the gridview with CommandName ="Filter"

Related

Not able to access dynamically generated templated field controls

I am creating dynamic Template Fields for my gridview:
<asp:GridView ID="grdData" runat="server" DataKeyNames = "ID" AutoGenerateColumns="false" OnRowDataBound="grdData_RowDataBound">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="editbtn" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
the code to add templateField is below:
private void BindGridView(DataTable dtData)
{
foreach (DataColumn item in dtData.Columns)
{
TemplateField tfield = new TemplateField();
tfield.HeaderText = item.ToString();
grdData.Columns.Add(tfield);
}
grdData.DataSource = dtData;
ViewState["dtDataTable"] = dtData;
grdData.DataBind();
}
and in row databound I am adding textbox and label to the templatefield:
protected void grdData_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataTable dtData = (DataTable)ViewState["dtDataTable"];
if (e.Row.RowType == DataControlRowType.DataRow)
{
int i = 1;
foreach (DataColumn item in dtData.Columns )
{
TextBox txtBox = new TextBox();
txtBox.ID = "txt"+item.ToString();
txtBox.Text = (e.Row.DataItem as DataRowView).Row[item.ToString()].ToString();
txtBox.Visible = false;
e.Row.Cells[i].Controls.Add(txtBox);
Label lblBox = new Label();
lblBox.ID = "lbl" + item.ToString();
lblBox.Text = (e.Row.DataItem as DataRowView).Row[item.ToString()].ToString();
e.Row.Cells[i].Controls.Add(lblBox);
i++;
}
}
}
Everything is working good so far,The grid is getting created and the values are getting populated ,but when i am calling below method and try to access the gridview control ,its throwing object reference error:
protected void OnCheckedChanged(object sender, EventArgs e)
{
bool isUpdateVisible = false;
CheckBox chk = (sender as CheckBox);
if (chk.ID == "chkAll")
{
foreach (GridViewRow row in grdData.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked = chk.Checked;
}
}
}
CheckBox chkAll = (grdData.HeaderRow.FindControl("chkAll") as CheckBox);
chkAll.Checked = true;
foreach (GridViewRow row in grdData.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
for (int i = 1; i < row.Cells.Count; i++)
{
Label test= row.FindControl("lblName") as Label;//this is coming null
Below code lines are throwing object reference error as they are not able to find control
row.Cells[i].Controls.OfType<Label>().FirstOrDefault().Visible = !isChecked;//this line throwing object reference error
if (row.Cells[i].Controls.OfType<TextBox>().ToList().Count > 0)
{
row.Cells[i].Controls.OfType<TextBox>().FirstOrDefault().Visible = isChecked;
}
if (row.Cells[i].Controls.OfType<DropDownList>().ToList().Count > 0)
{
row.Cells[i].Controls.OfType<DropDownList>().FirstOrDefault().Visible = isChecked;
}
if (isChecked && !isUpdateVisible)
{
isUpdateVisible = true;
}
if (!isChecked)
{
chkAll.Checked = false;
}
}
}
}
btnUpdate.Visible = isUpdateVisible;
}
Edit:
I tried reinistialising the controls in preinit event but still no luck:
protected void Page_PreInit(object sender, EventArgs e)
{
if (ViewState["gridData"] != null)
{
BindGridView((DataTable)ViewState["gridData"]);
}
}
What I am doing wrong?
I recreated the dynamic gridview Controls in OnRowCreated as this event gets called in every postback instead of onRowDataBound Event and it worked like charm.

right click on linkbutton in gridview is not opening into new tab

I am using a linkbutton within a gridview control.I want to open the link into a new tab. Link button:
<asp:LinkButton ID="lbtnEditCompany" CssClass="ahrefSearch" Text="Select" runat="server" OnClick="lbtnEditCompany_Click" />
Source Code :
protected void lbtnEditCompany_Click(object sender, EventArgs e)
{
try
{
LinkButton button = (LinkButton)sender;
SiteID = button.CommandArgument;
DataSet set = DataAccess.GetAllCorporateSites(SearchbyAlphabet, SessionManager.SaleID, SearchbyAssociate);
string str = "";
for (int i = 0; (i < set.Tables[0].Rows.Count) && (str == ""); i++)
{
if (SiteID == set.Tables[0].Rows[i]["ID"].ToString())
{
str = set.Tables[0].Rows[i]["CompanyName"].ToString();
}
}
SessionManager.WidgetId = Convert.ToInt32(SiteID);
SessionManager.SalesPersonSiteName = str;
base.Response.Redirect("~/Corporate/WidgetDetails.aspx", false);
}
catch (Exception exception)
{
HandlePageError(exception);
}
}
Try below code
Response.Write(String.Format("window.open('{0}','_blank')", ResolveUrl("~/Corporate/WidgetDetails.aspx")));

if i am deleting a row(ipaddress) in 2nd page of gridview it is deleting the first row in firstpage

\mycode
protected void btnRemove_Click(object sender, EventArgs e)
{
try
{
Button lbl = (Button)sender;
GridViewRow gv = (GridViewRow)lbl.NamingContainer;
int rowID = gv.RowIndex - 1;
if (ViewState["dt"] != null)
{
DataTable dt = (DataTable)ViewState["dt"];
// if (dt.Rows.Count > 1)
//{
//Remove the Selected Row data
dt.Rows.Remove(dt.Rows[gv.RowIndex]);
// }
//Store the current data
ViewState["dt"] = dt;
//Re bind the GridView for the updated data
gridIP.DataSource = dt;
gridIP.DataBind();
hdnCount.Value = gridIP.Rows.Count.ToString();
HidingRowID();
if (gridIP.Rows.Count == 0)
{
ReqFromIP.Enabled = true;
ValreqFromIP.Enabled = true;
ReqToIP.Enabled = true;
ValreqToIP.Enabled = true;
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "Plese specify at least one IP Range." + "');", true);
}
else
{
ReqFromIP.IsValid = true;
ReqFromIP.Enabled = false;
ValreqFromIP.Enabled = false;
ReqToIP.IsValid = true;
ReqToIP.Enabled = false;
ValreqToIP.Enabled = false;
}
}
}
catch (Exception ex)
{
Logging.LogExeption(ex);
}
}
protected void gridIP_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridIP.PageIndex = e.NewPageIndex;
gridIP.DataSource = (DataTable)ViewState["dt"];
gridIP.DataBind();
}

gridview programming using c sharp

How can i get multiple selected rows in gridview using c# code & that selected rows i have to display in another form which also have gridview
public partial class WindowForm: Form
{
private DataTable dataTable = new DataTable();
//This will contain all the selected rows.
private List<DataGridViewRow> selectedRows = new List<DataGridViewRow>();
public WindowForm()
{
InitializeComponent();
dataTable .Columns.Add("Column1");
dataTable .Columns.Add("Column2");
dataTable .Columns.Add("Column3");
for (int i = 0; i < 30; i++)
{
dataTable .Rows.Add(i, "Row" + i.ToString(), "Item" + i.ToString());
}
dataGridView1.DataSource = dataTable ;
//This will select full row of a grid
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
//This will allow multi selection
dataGridView1.MultiSelect = true;
dataGridView1.CurrentCellChanged += new EventHandler(dataGridView1_CurrentCellChanged);
dataGridView1.CellBeginEdit += new DataGridViewCellCancelEventHandler(dataGridView1_CellBeginEdit);
}
void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
PerformSelection(dataGridView1, selectedRows);
}
void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
{
if (selectedRows.Contains(dataGridView1.CurrentRow))
{
selectedRows.Remove(dataGridView1.CurrentRow);
}
else
{
selectedRows.Add(dataGridView1.CurrentRow);
}
PerformSelection(this.dataGridView1, selectedRows);
}
private void PerformSelection(DataGridView dgv, List<DataGridViewRow> selectedRowsCollection)
{
foreach (DataGridViewRow dgvRow in dgv.Rows)
{
if (selectedRowsCollection.Contains(dgvRow))
{
dgvRow.Selected = true;
}
else
{
dgvRow.Selected = false;
}
}
}
}

checking if gridview has a selected item

I have a grideview and 2 buttons. I need to only show the buttons when the gridview has a selected item. My code looks like this:
protected void Page_Load(object sender, EventArgs e)
{
btactivate.Visible = false;
btdeactivate.Visible = false;
//Show Activate and Deactivate Buttons only if an item in the gridview is selected
if (GridView1.SelectedIndex != -1)
{
btactivate.Visible = true;
btdeactivate.Visible = true;
}
else
{
btactivate.Visible = false;
btdeactivate.Visible = false;
}
}
But the problem I have now is that only when I select the second time a item in the gridview the buttons show up. I need to have the the buttons show when I select the first time. I have tried changing the selected index to "-0" but that shows the buttons all the time (even when I dont have something selected). Can anyone please help?
Try this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("Col1");
dt.Columns.Add("Col2");
dt.Columns.Add("Col3");
for (int i = 0; i < 20; i++)
{
DataRow dr = dt.NewRow();
dr["Col1"] = string.Format("Row{0}Col1", i + 1);
dr["Col2"] = string.Format("Row{0}Col2", i + 1);
dr["Col3"] = string.Format("Row{0}Col3", i + 1);
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
SetButtonState();
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
SetButtonState();
}
private void SetButtonState()
{
btactivate.Visible = GridView1.SelectedIndex > -1;
btdeactivate.Visible = GridView1.SelectedIndex > -1;
}

Categories

Resources