i am getting the data from gridview on rowcommand event by the following code
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "editproject")
{
string rowindex = e.CommandArgument.ToString();
int index = int.Parse(rowindex);
GridViewRow row = GridView2.Rows[index];
Label6.Text = row.Cells[1].Text;
}
}
but it would give only the data of the field that is visible in gridview row .how can i get the field that is not visible but bound to the gridview.
You can't get the value that you set to invisible because these were not rendered at the client side and can't be grabbed on the server side.
Alternatively you can store the value in hidden field and then you can get it from hidden field.
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show(dataGridView1.SelectedRows[0].Cells[0].Value.ToString ());
}
You can,t get the invisible bound elements but you can get the value from data source .For example you save data in data table which assigned to grid .Store this data table in view-state and on row command get data-key of that row and retrieved value through data table
You can get a command-like button which is invisible in the gridview, just look at this:---
False visibility of button requires you to have changed the property EnableEventValidation="False" on the page directive in default.aspx
private void grd_bind()
{
SqlDataAdapter adp = new SqlDataAdapter("select* from tbbook", ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lk = (LinkButton)(e.Row.Cells[5].Controls[0]);
e.Row.Attributes["Onclick"] = ClientScript.GetPostBackClientHyperlink(lk, "");
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = GridView1.SelectedRow.Cells[0].Text;
TextBox2.Text = GridView1.SelectedRow.Cells[1].Text;
TextBox3.Text = GridView1.SelectedRow.Cells[2].Text;
TextBox4.Text = GridView1.SelectedRow.Cells[3].Text;
TextBox5.Text = GridView1.SelectedRow.Cells[4].Text;
}
then in the default.aspx page, set EnableEventValidation
<%# Page Language="VB" EnableEventValidation="false" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
Related
I have a header DDL in my gridview that for some reason does not keep my selected value but rather binds the gridview and the header back to "starting position"
In my DDL header for Priority i have selected value '99' but after that my header gets back to starting position of my ListItem (that is Priority)
<HeaderTemplate>
<asp:DropDownList ID="ddlPriorityHeader" AutoPostBack="True" AppendDataBoundItems="True" OnSelectedIndexChanged="ddlHeader_SelectedIndexChanged" runat="server">
<asp:ListItem>Priority</asp:ListItem>
</asp:DropDownList>
</HeaderTemplate>
I have a RowDatabound for the gridview but there i do nothing more then find the DDL for the header and then bound the DDL.
protected void gwActivity_RowDataBound(object sender, GridViewRowEventArgs e)
{
//.............. some code.....//
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT DISTINCT [Priority] FROM [BI_Planning].[dbo].[tblPriority]", con);
con.Open();
ddlPriority.DataSource = cmd.ExecuteReader();
ddlPriority.DataTextField = "Priority";
ddlPriority.DataBind();
}
}
I have put my gridview in a method:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridviewActivity();
}
}
Can it be that im bounding my DDL everytime for my gridview? im stuck here....
You need to store ddlPriority selected text in temp place like ViewState that will keep value between postbacks.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["PriorityText"] = "Priority";
BindGridviewActivity();
}
}
And aftrt ddlPriority.DataBind(); set selectd text to ViewState value
ddlPriority.Items.FindByText(ViewState["PriorityText"].ToString()).Selected = true;
And in your ddlHeader_SelectedIndexChanged set ViewState to selected text
protected void ddlHeader_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlHeader = (DropDownList)sender;
ViewState["PriorityText"] = ddlHeader.SelectedItem.Text;
}
Check this complete example for more details
I have a gridview that loads data from a stored procedure.
OBJECTIVE:
to make the full gridview row clickable by hiding the select column in the gridview - I was able to do this by doing the code below in the RowDataBound event.
Next is when I click a full row in the gridview, I should be able to get the data / values from the row selected and display this in the textboxes in the modal pop up to appear. This is for UPDATING / EDITING FUNCTIONS.
Here's what I have got
protected void grdTenant_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Style["display"] = "none";
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] =
"javascript:setMouseOverColor(this);";
e.Row.Attributes["onmouseout"] =
"javascript:setMouseOutColor(this);";
e.Row.Attributes["onclick"] =
Page.ClientScript.GetPostBackClientHyperlink
(this.grdTenant, "Select$" + e.Row.RowIndex);
e.Row.Attributes.Add("onclick", String.Format("javascript:$find('{0}').show();",ModalEditTenant.ClientID ));
//this line does not work in retrieving row data
IDataRecord dataRow = (IDataRecord)e.Row.DataItem;
txtRPCode.Text = Convert.ToString(dataRow["Retail Partner"]);
}
}
As an alternative, I do this to achieve the second goal but fails to do the first
protected void grdTenant_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = grdTenant.SelectedRow;
txtRPCode.Text = row.Cells[1].Text;
ModalEditTenant.Show();
}
But, this method works only when the select button column is visible and when it is clicked, it fails to do so when the full row is selected.
How can I make the full row select and retrieves the data to textbox successfully (with the select column hidden)
This is how gridview bind the data from the stored procedure datasource.
System.Threading.Thread.Sleep(500);
//DropDownList ddl = (DropDownList)sender;
SqlCommand cmd = new SqlCommand("spTenantList", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Location", ddlSelectLoc.SelectedValue );
try
{
con.Open();
grdTenant.EmptyDataText = "No Records Found";
grdTenant.DataSource = cmd.ExecuteReader();
grdTenant.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
Use FindControl()method.
Instead of txtRetailPartner place your TextBox ID.
txtRPCode.Text = ((TextBox)e.Row.FindControl("txtRetailPartner")).Text;
Use my logic below in RowDataBound event to get DataItem:
protected void grdTenant_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Style["display"] = "none";
if (e.Row.RowType == DataControlRowType.DataRow)
{
IDataRecord dataRow = (IDataRecord)e.Row.DataItem;
txtRPCode.Text = Convert.ToString(dataRow["Retail Partner Code"]);
}
}
I have found the answer based on what is to achieved. Using my current codes posted as question , Just remove the one line code there and it will work
protected void grdTenant_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Style["display"] = "none";
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] =
"javascript:setMouseOverColor(this);";
e.Row.Attributes["onmouseout"] =
"javascript:setMouseOutColor(this);";
e.Row.Attributes["onclick"] =
Page.ClientScript.GetPostBackClientHyperlink
(this.grdTenant, "Select$" + e.Row.RowIndex);
}
}
This line is removed:
//This is no longer needed as it will make the onselectedindexchanged event ineffective as this will be run first.
e.Row.Attributes.Add("onclick", String.Format("javascript:$find('{0}').show();",ModalEditTenant.ClientID ));
protected void grdTenant_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = grdTenant.SelectedRow;
txtRPCode.Text = row.Cells[1].Text;
ModalEditTenant.Show();
}
And everything will work as expected.
I have two LinkButton's called Approve and Reject in my GridView and I want my Approve LinkButton to be Disabled when click on it. I tried the following code but it's not working.
protected void gvManagerTimeSheet_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ApproveRow")
{
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
LinkButton lnkbtn = (LinkButton)row.FindControl("lbApprove");
lnkbtn.Enabled = false;
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
int TimeSheetId = Convert.ToInt32(e.CommandArgument);
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spApproveTimeSheet ", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#TimeSheetId", TimeSheetId);
con.Open();
cmd.ExecuteNonQuery();
GetManagerTimeSheets();
}
}
}
Well you haven't shown your aspx link button so i assuming that your link button is this
<asp:LinkButton id="linkBtn" runat="server" text="Approve" OnClientClick="Disable(this);"/>
Now you should add a javascript function like this on the page::
<script>
function Disable(link)
{
link.disabled = result;
}
</script>
Now when you click on the page your button will get disabled.
try this
LinkButton lbApprove = (LinkButton)e.Row.Cells[0].Controls[0];
You need to Rebind the grid with disabled control, but also you need to check the status in itembound event and disable. For that you can use session or hidden field.
protected void rg_OnItemCommand(object source, GridCommandEventArgs e)
{
// your logic
hdFlag.value = "val" // id of the data item to hide if more than one use array
// rebind logic for gird
}
protected void rg_ItemDataBound(object sender, GridItemEventArgs e)
{
if(hdFlag.value == "id")
{
// Find the control and hide
}
}
When trying to update GridView data, it successfully runs, but it gets the old data instead of the data you type in the textboxes.
This is what I have:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string name = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
string phone = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text;
string email = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text;
int contactId = Convert.ToInt32(((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text);
objLogic.UpdateContact(name, phone, email, contactId); //passes values to SQL to update database
GridView1.EditIndex = -1;
GridView1.DataBind();
}
and
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
and
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.DataSource = objLogic.LoadClient();
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "clientId";
DropDownList1.DataBind();
}
GridView1.DataSource = objLogic.LoadContacts(Convert.ToInt16(DropDownList1.SelectedValue));
GridView1.DataBind();
For example, the current data is:
name: Blake, phone: 123-234-3456, email: test#test.com, contactId: 22
I type in new data:
name: John, phone: 555-555-5555, email: test2#test2.com, contactId: 22
Data that ends up in the database:
name: Blake, phone: 123-234-3456, email: test#test.com, contactId: 22
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.DataSource = objLogic.LoadClient();
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "clientId";
DropDownList1.DataBind();
BindGrid();
}
}
protected void BindGrid()
{
GridView1.DataSource = objLogic.LoadContacts(Convert.ToInt16(DropDownList1.SelectedValue));
GridView1.DataBind();
}
Every time the page posts back you are rebinding the grid. Move the binding of the grid into a separate function. After you do the row updating, rebind the grid.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string name = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
string phone = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text;
string email = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text;
int contactId = Convert.ToInt32(((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text);
objLogic.UpdateContact(name, phone, email, contactId); //passes values to SQL to update database
GridView1.EditIndex = -1;
BindGrid();
}
When you edit you must call BindGrid too.
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
//GridView1.DataBind(); this is meaningless, you have not set a DataSource
BindGrid();
}
When you raise the RowUpdating event your basically getting the values BEFORE the GridView updates the row. This is basically so you can cancel the update operation. To get what you've type in I think you need to get the new values (the Dictionary e.NewValues() in your case).
In your case you can use it something like this (assuming name, phone and email are what they're called in your gridview):
foreach(DictionaryEntry de in e.NewValues())
{
string name = de.FirstOrDefault(x => x.Key == "name").Value;
string phone = de.FirstOrDefault(x => x.Key == "phone").Value;
string email = de.FirstOrDefault(x => x.Key == "email").Value;
}
NOTE: If you're simply using this to get the values typed in to update your database then you're better of binding the datagrid and use the value after that to ensure you definitely have the same values in the datagrid as to what you put into the database. Alternatively, use the RowUpdated event instead of the RowUpdating event.
The most prevalent reason is that we usually forgot to check the postbacks in the Page Load event.
check the post-back, then the problem will be removed.
if (! IsPostBack)
{
readData();
...
}
Prokzy I have just your example on my side and doing something like this worked fine for me. notice the DataSource portion. I have a DataSet instantiated as aDataSet btw
protected void GridView1_GridViewPageEventArgs e(object sender, GridViewPageEventArgs e)
{
GridView1.EditIndex = e.NewPageIndex;
GridView1.DataSource = null;
GridView1.DataSource = aDataset;
GridView1.DataBind();
}
You need to call LoadContacts again and reassign GridView1.DataSource after the database is updated. Currently, the DataSource is not being updated - and is just using the collection that was retrieved prior to the row update.
I asked a similar question to this but the circumstances have changed.
I bind my gridview through code rather than on the source.
The pagination works fine, but if I click a button on second page of the gridview (after pagination), the postback is causing the pagination to reset to page 1. Can anyone tell me what I'm doing wrong?
Within my pageload i have set the !POSTBACK method as shown i.e if there is postback event, then it shouldn't reset the grid but it does!
Heres the onload:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["usersName"] != null)
{
object a = Session["_id"];
IDMaster = Convert.ToInt32(a);
GridView1.Columns[10].Visible = true;
GridView1.Columns[11].Visible = true;
}
else
{
GridView1.Columns[10].Visible = false;
GridView1.Columns[11].Visible = false;
}
if (!IsPostBack)
{
BindGrid();
}
The BindGrid();
SqlConnection sqlcon = new SqlConnection(connstring);
SqlCommand sqlcmd = new SqlCommand("select * from Coffees ORDER BY coffeeName ASC", sqlcon);
SqlDataAdapter adp = new SqlDataAdapter(sqlcmd);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
Page index method:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
if(ViewState["searchTerm"] != null)
{
object a = ViewState["searchTerm"];
string reloadTerm = a.ToString();
setGrid(reloadTerm);
}
You need to bind your gridview in GridView1_PageIndexChanging event
GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
if(ViewState["searchTerm"] != null)
{
object a = ViewState["searchTerm"];
string reloadTerm = a.ToString();
setGrid(reloadTerm);
}
BindGrid();
}
hopefully it works for you.
Since you are binding grid view dynamically, Please remove
if (!IsPostBack)
condition from page load. Grid view needs binding every time.
I found this issue. I forgot that after I add an item to my cart i was calling response.redirect to refresh the page....obviously this meant the page was recalled refreshing the page so the grid was always going to reset. Thanks again.