How to call RowDataBound event in Button Click event in asp.net? - asp.net

protected void GVPaperrate_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataTable dtbirdtype = new DataTable();
objRetailPL.status = 5;
dtbirdtype = objRetailBAL.GetType(objRetailPL);
DropDownList ddl1 = (DropDownList)e.Row.FindControl("ddlType");
if (ddl1 != null)
{
ddl1.DataSource = dtbirdtype;
ddl1.DataTextField = "birdname";
ddl1.DataValueField = "sno";
ddl1.DataBind();
ddl1.Items.Add(new ListItem("--Select--", "0"));
ddl1.SelectedIndex = ddl1.Items.Count - 1;
}
DataTable dtzonedet = new DataTable();
dtzonedet = objRetailBAL.GetZoneDet();
DropDownList ddlzone = (DropDownList)e.Row.FindControl("ddlzone");
if (ddlzone != null)
{
ddlzone.DataSource = dtzonedet;
ddlzone.DataTextField = "ZoneName";
ddlzone.DataValueField = "SNo";
ddlzone.DataBind();
ddlzone.Items.Add(new ListItem("--Select--","0"));
ddlzone.SelectedIndex=ddlzone.Items.Count-1;
}
}protected void btngo_Click(object sender, ImageClickEventArgs e)
{
DataTable dtinsert = new DataTable();
objRetailPL.ZoneName = txtzone.Text.ToString();
objRetailPL.Username = Session["Username"].ToString();
dtinsert = objRetailBAL.InsertZone(objRetailPL);
if (dtinsert.Rows.Count > 0)
{
if (dtinsert.Rows[0]["status"].ToString() == "2")
{
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "insert", "alert('Saved Successfully')", true);
//GVPaperrate.DataBind();
txtzone.Text = "";
}
else if (dtinsert.Rows[0]["status"].ToString() == "1")
{
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "insert", "alert('ZoneName Already Exists')", true);
}
}
else
{
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "insert", "alert('Insertion Failed Please Consult IT Department')", true);
}
}
How to call RowDataBound in button Click event.I want result as if click on go button it will automatically show entered data in dropdownlist.But am not getting like that. What i have to do please help me.

Bind the grid after click of Go button or Bind the grid on Page_PreRender() method.

I think you are inserting data in the database. After inserting get the data and bind with gridview.
Try this,
GVPaperrate.DataBind();
Why you comment this line.You should un-comment this it will work.
Your Button Click code
protected void btngo_Click(object sender, ImageClickEventArgs e)
{
DataTable dtinsert = new DataTable();
objRetailPL.ZoneName = txtzone.Text.ToString();
objRetailPL.Username = Session["Username"].ToString();
dtinsert = objRetailBAL.InsertZone(objRetailPL);
if (dtinsert.Rows.Count > 0)
{
if (dtinsert.Rows[0]["status"].ToString() == "2")
{
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "insert", "alert('Saved Successfully')", true);
**GVPaperrate.DataBind()**; //why you comment this
txtzone.Text = "";
}
else if (dtinsert.Rows[0]["status"].ToString() == "1")
{
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "insert", "alert('ZoneName Already Exists')", true);
}
}
else
{
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "insert", "alert('Insertion Failed Please Consult IT Department')", true);
}
}

Related

asp.net clear row selection for Multiple Grid with Single Button Click

Hi Friends i have created a single asp.net page(c#) with multiple grid view to display records. I have multiple command button to show records in these grid.
I am using single button to clear the row selection in grid but it is not working.
Please help me...
protected void btnClearGridSelection_Click(object sender, EventArgs e)
{
if (GridView1.Visible == true)
{
GridView1.SelectedIndex = -1;
}
if (GridView1.Visible == true)
{
GridViewSearch.SelectedIndex = -1;
}
if (GridView1.Visible == true)
{
GridViewState.SelectedIndex = -1;
}
if (GridView1.Visible == true)
{
GridViewDistrict.SelectedIndex = -1;
}
if (GridView1.Visible == true)
{
GridViewType.SelectedIndex = -1;
}
if (GridView1.Visible == true)
{
GridViewEmployee.SelectedIndex = -1;
}
}
//---------------------updating my question with new problem-------------
Now i am able to to clear the selection from row but facing new problem.......When i am clicking on show(to show results state wise) button it is showing results and also clearing the selection when clicking on clear selection button with no problems....but when i click on another show button(to show results district wise) to show results it is showing results but when i select the row and click on clear selection button it is showing both grid with records......please help how to hide state Grid when i am Clicking on Clear Selection Button while using District grid......i am posting the code which i am using on Button Click....
.......clear selection....Button click:
protected void btnClearGridSelection_Click(object sender, EventArgs e)
{ GridView1.SelectedIndex = -1;
GridViewSearch.SelectedIndex = -1;
GridViewState.SelectedIndex = -1;
GridViewDistrict.SelectedIndex = -1;
GridViewType.SelectedIndex = -1;
GridViewEmployee.SelectedIndex = -1;
}
.......State Grid....Button click:
protected void btnState_Click(object sender, EventArgs e)
{
GridView1.Visible = false;
//GridViewState.Visible = true;
GridViewDistrict.Visible = false;
GridViewSearch.Visible = false;
GridViewType.Visible = false;
GridViewEmployee.Visible = false;
btnClearGridSelection.Visible = true;
string d2 = ddlState.Text;
string strquery = "select * from tblAsset2 where v_State=#d2";
if (con.State != ConnectionState.Closed)
{
con.Close();
}
con.Open();
try
{
SqlCommand cmd = new SqlCommand(strquery, con);
cmd.Parameters.AddWithValue("#d2", d2);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridViewState.DataSource = ds;
GridViewState.DataBind();
int rowCount = GridViewState.Rows.Count;
if (rowCount <= 0)
{
Label67.Visible = true;
GridViewState.Visible = false;
Label67.Text = "Sorry!....Records not found.";
}
else
{
GridViewState.Visible = true;
Label67.Visible = false;
}
}
catch (Exception ex)
{
Response.Write(ex);
}
finally
{
con.Close();
}
}
....................District Grid....Button click:
protected void btnDistrict_Click(object sender, EventArgs e)
{
GridView1.Visible = false;
GridViewDistrict.Visible = false;
//GridViewDistrict.Visible = true;
GridViewSearch.Visible = false;
GridViewType.Visible = false;
GridViewEmployee.Visible = false;
btnClearGridSelection.Visible = true;
string d2 = ddlDistrict.Text;
string strquery = "select * from tblAsset2 where v_District=#d2";
if (con.State != ConnectionState.Closed)
{
con.Close();
}
con.Open();
try
{
SqlCommand cmd = new SqlCommand(strquery, con);
cmd.Parameters.AddWithValue("#d2", d2);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridViewDistrict.DataSource = ds;
GridViewDistrict.DataBind();
int rowCount = GridViewDistrict.Rows.Count;
if (rowCount <= 0)
{
Label67.Visible = true;
GridViewDistrict.Visible = false;
Label67.Text = "Sorry!....Records not found.";
}
else
{
GridViewDistrict.Visible = true;
Label67.Visible = false;
}
}
catch (Exception ex)
{
Response.Write(ex);
}
finally
{
con.Close();
}
}
I resolved my problem and it may help someone else so i am posting it.. i have written wrong line:- GridViewState.Visible = true; // i have commented this line and error gone
protected void GridViewState_RowCreated(object sender, GridViewRowEventArgs e)
{
GridViewState.Visible = true; // i have commented this line and error gone
}

UserAccounts_RowEditing/Updating is not working properly

Alright, so I have a Gridview and added RowEditing and RowUpdating to it, but it won't really edit something.. This is my code for both:
protected void UserAccounts_RowEditing(object sender, GridViewEditEventArgs e)
{
UserAccounts.EditIndex = e.NewEditIndex;
BindUserAccounts();
}
protected void UserAccounts_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = UserAccounts.EditIndex;
GridViewRow row = UserAccounts.Rows[e.RowIndex];
username = UserAccounts.Rows[e.RowIndex].Cells[1].Text;
email = ((TextBox)row.Cells[2].Controls[0]).Text;
MembershipUser user = Membership.GetUser(username);
if (user != null)
{
user.Email = email;
Membership.UpdateUser(user);
ActionStatus.Text = string.Format("User {0} details have been successfully updated!", username);
}
UserAccounts.EditIndex = -1;
BindUserAccounts();
}
What am I doing wrong in here?
EDIT: This is my BindUserAccounts:
private void BindUserAccounts()
{
int totalRecords;
UserAccounts.DataSource = Membership.FindUsersByName(this.UsernameToMatch + "%", this.PageIndex, this.PageSize, out totalRecords);
UserAccounts.DataBind();
bool visitingFirstPage = (this.PageIndex == 0);
lnkFirst.Enabled = !visitingFirstPage;
lnkPrev.Enabled = !visitingFirstPage;
int lastPageIndex = (totalRecords - 1) / this.PageSize;
bool visitingLastPage = (this.PageIndex >= lastPageIndex);
lnkNext.Enabled = !visitingLastPage;
lnkLast.Enabled = !visitingLastPage;
}
i think the should be like this
protected void update_click_foredu(object sender, GridViewUpdateEventArgs e)
{
Label edui = (Label)edugrid.Rows[e.RowIndex].FindControl("label");
TextBox unitxt = (TextBox)edugrid.Rows[e.RowIndex].FindControl("txtuni");
if (unitxt != null && costxt != null && startdatetxt != null && enddatetxt != null)
{
using (Entities1 context = new Entities1())
{
string eduID = edui.Text;
model obj = context.entitytabel.First(x => x.ID == eduID);
obj.Univ_Name = unitxt.Text;
context.SaveChanges();
lblMessage.Text = "Saved successfully.";
edugrid.EditIndex = -1;
bindgrid();
}
}
}
here im using EF like this you can find the control of the text box and save it in gridview
hope this helps you
Somehow it works now after editing the GridView and set "UserName", "IsApproved", "IsLockedOut" and "IsOnline" to ReadOnly="true"

checkboxlist selectedindexchanged event c# not working

I've got a checkboxlist on my asp.net page. I'm populating it with countries. I've added a "SelectedIndexChanged" event that is supposed to check that if one of the selected countries is Africa, it should make a textbox visible, otherwise visible=false if it is not selected. I have changed the AutoPostback to true. But the problem that I'm having is that it is not doing an autopostback (it's not going into the method at all). Could somebody please help me on this?
This is what I've done:
<div id="div1" style="overflow-x:auto; width:100%; max-width:100%; height:150px; max-height:150px;" runat="server">
<asp:CheckBoxList ID="lstLocations" CssClass="CheckBoxList" runat="server" Width="40%" Height="100%" AutoPostBack="True" OnSelectedIndexChanged="lstLocations_SelectedIndexChanged" >
</asp:CheckBoxList>
</div>
Populating the checkboxlist:
private void CreateRegionList()
{
lstLocations.Items.Clear();
cn = new SqlConnection(GetConnectionString());
SqlCommand myCmd = new SqlCommand("SELECT ID, Region FROM CanonSALeads_Region ORDER BY Region", cn);
cn.Open();
SqlDataReader myReader = myCmd.ExecuteReader();
lstLocations.AutoPostBack = false;
lstLocations.CellPadding = 5;
lstLocations.CellSpacing = 5;
lstLocations.RepeatColumns = 1;
lstLocations.RepeatDirection = RepeatDirection.Vertical;
lstLocations.RepeatLayout = RepeatLayout.Flow;
lstLocations.TextAlign = TextAlign.Right;
lstLocations.CssClass = "CheckBoxList";
if (myReader.HasRows)
{
while (myReader.Read())
{
CheckBox cb = new CheckBox();
cb.ID = myReader[0].ToString();
cb.Text = myReader[1].ToString();
cb.AutoPostBack = false;
cb.CssClass = "CheckBox";
lstLocations.Items.Add(new ListItem(myReader[1].ToString(), myReader[0].ToString()));
lstLocations.Controls.Add(new LiteralControl("<br>"));
}
}
cn.Close();
myReader.Close();
}
And this is my selectedIndexChanged event:
protected void lstLocations_SelectedIndexChanged(object sender, EventArgs e)
{
string value = null;
try
{
foreach (ListItem checkBox in lstLocations.Items)
{
if (checkBox.Selected == true)
{
value = checkBox.Text;
if (value == "Africa")
{
txtCountryOfAfrica.Visible = true;
lblAfricaCountry.Visible = true;
}
}
else
{
value = checkBox.Text;
if (value == "Africa")
{
txtCountryOfAfrica.Visible = false;
lblAfricaCountry.Visible = false;
}
}
}
}
catch (Exception ex)
{
string msg = "Select Error:";
msg += ex.Message;
throw new Exception(msg);
}
}
Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
txtUser.Text = userName;
if (!IsPostBack)
{
ContainerDocumentation.ActiveTab = tabAddCustomer;
PopulateSector();
CreateRegionList();
PopulateOpportunitySource();
CreatelstProductGroupList();
PopulateStatus();
PopulateTenders();
PopulateOtherOpportunityType();
}
}
My guess: you are calling CreateRegionList in Page_Load without checking the IsPostBack property. That reloads all items from database and prevents this event from being triggered.
So check it:
protected bvoid Page_Load(Objject sender, EventArgs e)
{
if(!IsPostBack)
{
CreateRegionList();
}
}
That's because you have to set true to:
lstLocations.AutoPostBack = true;

Type Casting Issue with List View OnItemDataBound Event

On Page Load Event I am trying to do
protected void Page_Load(object sender, EventArgs e)
{
XmlReader reader = XmlReader.Create(FeedUrl);
SyndicationFeed feed = SyndicationFeed.Load(reader);
lstViewNewsFeeds.DataSource = feed.Items;
lstViewNewsFeeds.DataBind();
}
protected void lstViewNewsFeeds_ItemDataBound(object sender, ListViewItemEventArgs e)
{
try
{
// Instantiate listview control object.
ListViewDataItem lvDataItem = (ListViewDataItem)e.Item;
at this line given exception
**DataRowView drvItem = (DataRowView)lvDataItem.DataItem;**
//Make sure that data item is binding with listview.
if (lvDataItem.ItemType == ListViewItemType.DataItem)
{
SyndicationItem item = e.Item.DataItem as SyndicationItem;
LinkButton linkButtonTitle = (LinkButton)e.Item.FindControl("lbNewsTitle");
Panel panelNewsDescContent = (Panel)e.Item.FindControl("panelNewsDescription");
// Make sure that linkButtonTile is referenced.
if (linkButtonTitle != null)
{
// linkButtonTitle.Text = Convert.ToString(item.Title);
linkButtonTitle.Text = Convert.ToString(drvItem["Title"]);
}
// Make sure that panel object is referenced.
if (panelNewsDescContent != null)
{
Label lblBox = new Label();
// lblBox.Text = Convert.ToString(item.Summary);
panelNewsDescContent.Controls.Add(lblBox);
}
//Label l = e.Row.FindControl("Label1") as Label;
//l.Text = item.Title.Text;
//HyperLink hl = e.Row.FindControl("HyperLink1") as HyperLink;
//hl.Text = item.Title.Text;
//hl.NavigateUrl = item.Links[0].Uri.AbsoluteUri;
}
}
catch(Exception ee)
{
Response.Write(ee.Message);
}
Giving Error:
'System.Data.DataRowView'.Unable to cast object of type
'System.ServiceModel.Syndication.SyndicationItem' to type
'System.Data.DataRowView'.Unable to cast object of type
I am not able to understand how i remove this error. Please help me here.
SyndicationFeed.Items Property returns an IEnumerable<SyndicationItem>, so you should cast it to SyndicationItem instead.
SyndicationItem item = (SyndicationItem)lvDataItem.DataItem;
i have tried this works fine.
SyndicationItem item = e.Item.DataItem as SyndicationItem;
protected void lstViewNewsFeeds_ItemDataBound(object sender, ListViewItemEventArgs e)
{
try
{
// Instantiate listview control object.
ListViewDataItem lvDataItem = (ListViewDataItem)e.Item;
//DataRowView drvItem = (DataRowView)lvDataItem.DataItem;
//SyndicationItem item = (SyndicationItem)lvDataItem.DataItem;
//Make sure that data item is binding with listview.
if (lvDataItem.ItemType == ListViewItemType.DataItem)
{
SyndicationItem item = e.Item.DataItem as SyndicationItem;
LinkButton linkButtonTitle = (LinkButton)e.Item.FindControl("lbNewsTitle");
Panel panelNewsDescContent = (Panel)e.Item.FindControl("panelNewsDescription");
// Make sure that linkButtonTile is referenced.
if (linkButtonTitle != null)
{
// linkButtonTitle.Text = Convert.ToString(item.Title);
linkButtonTitle.Text = Convert.ToString(item.Title.Text);
}
// Make sure that panel object is referenced.
if (panelNewsDescContent != null)
{
Label lblBox = new Label();
lblBox.Text = Convert.ToString(item.Summary);
panelNewsDescContent.Controls.Add(lblBox);
}
//Label l = e.Row.FindControl("Label1") as Label;
//l.Text = item.Title.Text;
//HyperLink hl = e.Row.FindControl("HyperLink1") as HyperLink;
//hl.Text = item.Title.Text;
//hl.NavigateUrl = item.Links[0].Uri.AbsoluteUri;
}
}
catch(Exception ee)
{
Response.Write(ee.Message);
}
}
By The way thanks all of you for help.
Try this:
protected void lstViewNewsFeeds_ItemDataBound(object sender, ListViewItemEventArgs e)
{
try
{
//Make sure that data item is binding with listview.
if (lvDataItem.ItemType == ListViewItemType.DataItem)
{
SyndicationItem item = e.Item.DataItem as SyndicationItem;
LinkButton linkButtonTitle = (LinkButton)e.Item.FindControl("lbNewsTitle");
Panel panelNewsDescContent = (Panel)e.Item.FindControl("panelNewsDescription");
// Make sure that linkButtonTile is referenced.
if (linkButtonTitle != null)
{
linkButtonTitle.Text = Convert.ToString(item.Title);
}
// Make sure that panel object is referenced.
if (panelNewsDescContent != null)
{
Label lblBox = new Label();
lblBox.Text = Convert.ToString(item.Summary);
panelNewsDescContent.Controls.Add(lblBox);
}
Label l = e.Row.FindControl("Label1") as Label;
l.Text = item.Title.Text;
HyperLink hl = e.Row.FindControl("HyperLink1") as HyperLink;
hl.Text = item.Title.Text;
hl.NavigateUrl = item.Links[0].Uri.AbsoluteUri;
}
}
catch(Exception ee)
{
Response.Write(ee.Message);
}
}

asp.net - GridView dynamic footer row creation problem

I am able to create BoundFields and Footer-rows dynamically like this in my GridView:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
CreateGridView();
}
}
private void CreateGridView()
{
GridView1.Columns.Clear();
DataTable dataTable = Book.GetBooksDataSet().Tables[0];
CommandField cf = new CommandField();
cf.ShowEditButton = true;
GridView1.Columns.Add(cf);
int colCount = 1;
foreach (DataColumn c in dataTable.Columns)
{
BoundField boundField = new BoundField();
boundField.DataField = c.ColumnName;
boundField.HeaderText = c.ColumnName;
//boundField.FooterText = "---";
if (colCount == 3 || colCount == 5)
{
boundField.ReadOnly = true;
}
GridView1.Columns.Add(boundField);
colCount++;
}
GridView1.ShowFooter = true;
GridView1.DataSource = dataTable;
GridView1.DataBind();
GridViewRow footerRow = GridView1.FooterRow;
Button b = new Button();
b.Text = "Add New";
int i = 0;
footerRow.Cells[i].Controls.Add(b);
foreach (DataColumn c in dataTable.Columns)
{
++i;
TextBox tb = new TextBox();
footerRow.Cells[i].Controls.Add(tb);
}
}
....................................
....................................
....................................
}
But the problem is, when I click the "Add New" - button, it disappears instantly. And, also I am unable to add any event handler to it. Or intercept its actions like this:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Edit")
{
GridView1.EditIndex = index;
GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];
//We can get cell data like this
string id = selectedRow.Cells[1].Text;
string isbn = selectedRow.Cells[2].Text;
//This is necessary to GridView to be showed up.
CreateGridView();
}
else if (e.CommandName == "Update")
{
LinkButton updateButton = (LinkButton)e.CommandSource;
DataControlFieldCell dcfc = (DataControlFieldCell)updateButton.Parent;
GridViewRow gvr = (GridViewRow)dcfc.Parent;
//The update...................
//Update grid-data to database
UpdateDataInTheDatabase(gvr.Cells[1].Controls);
//Grid goes back to normal
GridView1.EditIndex = -1;
//This is necessary to GridView to be showed up.
CreateGridView();
}
}
One more thing, I have seen some solutions that suggests to handle the GridView's rowBound event. But I need to do it from within Page_load event handler, or in, GridView1_RowCommand event handler.
Dynamically created controls mus be re-created on every postback. Your "Add New" button causes a postback so the dynamically created footer disappears. Is there a reason this grid has to be created dynamically? From the code you posted it appears that you could do this in markup instead. If not, you'll have to re-create the dynamic controls on every postback.
Edited to add:
I played with this a little bit and what's below works in that the grid doesn't disappear and events are handled, but it doesn't actually do anything. Hope this helps.
Markup:
<p><asp:Literal ID="Literal1" runat="server" /></p>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnRowCommand="GridView1_RowCommand"
OnRowEditing="GridView1_RowEditing"/>
Code:
protected void Page_Load(object sender, EventArgs e)
{
BindGridView();
}
private DataTable GetBooksDataTable()
{
var dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Title", typeof(string));
dt.Columns.Add("Author", typeof(string));
for (int index = 0; index < 10; index++)
{
dt.Rows.Add(index, "Title" + index, "Author" + index);
}
return dt;
}
private void BindGridView()
{
var dt = GetBooksDataTable();
GridView1.Columns.Clear();
GridView1.ShowFooter = true;
var cf = new CommandField();
cf.HeaderText = "Action";
cf.ShowEditButton = true;
GridView1.Columns.Add(cf);
for (int index = 0; index < dt.Columns.Count; index++)
{
var boundField = new BoundField();
boundField.DataField = dt.Columns[index].ColumnName;
boundField.HeaderText = dt.Columns[index].ColumnName;
GridView1.Columns.Add(boundField);
}
GridView1.DataSource = dt;
GridView1.DataBind();
var footer = GridView1.FooterRow;
var b = new LinkButton();
b.Text = "Add New";
b.CommandName = "Add New";
footer.Cells[0].Controls.Add(b);
for (int index = 1; index < dt.Columns.Count + 1; index++)
{
var tb = new TextBox();
footer.Cells[index].Controls.Add(tb);
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Literal1.Text = e.CommandName;
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
Literal1.Text = "Editing row index " + e.NewEditIndex.ToString();
}
Move your code from Page_Load to Page_Init. Things added in the Page_Load last only for the lifecycle of one postback.
You'd then be able to add eventhandlers, intercept events etc.

Resources