If I have two buttons on gridview and each performing different function. For example my code below,
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
//Do something else
}
else if (e.CommandName == "View Cert")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
errorlab.Text = row.Cells[3].Text;
}
}
The value of cell 3 is a hidden field and there is a value in the database that's binding to hidden field but with my code I couldn't get the value. The errorlab label is showing nothing. Maybe I'm missing something.
I would like to suggest an answer, the command argument will not fetch you the row index. Instead it will give you what you bind during gridview data binding.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
//Do something else
}
else if (e.CommandName == "View Cert")
{
//The hidden field id is hdnProgramId
HiddenField hdnProgramId = (((e.CommandSource as LinkButton).Parent.FindControl("hdnProgramId")) as HiddenField);
}
}
This will try to locate the hidden field from the gridview row context.
If you have futher controls on the gridview cell then you have to access them using the Controls property
HiddenField hiddenField =row.Cells[3].Controls[0] as HiddenField;
if(hiddenField != null)
errorlab.Text = hiddenField.Value;
You have to use the correct index for the controls. Debug the code and check what is position of the control in row.Cells[3].Controls.
Always try to avoid referring cells by it's index position in gridview as it may result in changing the code if you happen to add/delete few more columns in the grid in the future which might result in undesired result. Also note that hiddenfield does not have a Text property but rather a Value property to access it's value.
If you know the hiddenfield's name then better try accessing it by it's name. Let's say you have your hiddenfield defined as below in your gridview
<ItemTemplate>
<asp:HiddenField ID ="hdnField" runat="server" Value='<%# Bind("ErrorLab") %>'/>
</ItemTemplate>
Then in your GridView1_RowCommand you can do
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
HiddenField hdnField = (HiddenField)row.FindControl("hdnField");
errorlab.Text = hdnField.Value;
Related
I am creating the dynamic grid and adding textbox and label in row dynamically on some button click and bind some data from the database to textbox and label.I want to change the label text color and text box read only for condition depend on database.i have used onRowDataBound event of gridview but not getting any value in the textbox and label for a row. Can anyone helps me to solve this issue? Thanks
protected void grdMasterData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label status = e.Row.FindControl("lblProduct") as Label;
if (status.Text == "LY Actuals")
{
e.Row.Cells[0].CssClass = "lblProductColor";
// lbtAction.Visible = false;
}
}
}
In RowDataBound three row types provided by grid, you are using only DataRow, try to get your values from empty row and footer row because first record will not come in DataRow.
I have a gridview that pulls data from local SQL server. I chose 3 columns to be displayed on the gridview. I added a fourth column (select command). I would like to get the data from the first column which is an id when I click the select command but i always get an error "An exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll but was not handled in user code Additional information: Index was out of range. Must be non-negative and less than the size of the collection."
Basically I would like to get the id from the first column then assign it to a session variable then redirect to a second page and then use the content of that session variable to populate another textbox.
protected void grdClients_RowCommand(object sender, GridViewCommandEventArgs e)
{
string id = grdClients.Rows[grdClients.SelectedIndex].Cells[0].Text.ToString();
Session["ID"] = id;
Response.Redirect("secondPage.aspx");
}
Any suggestions?
Thanks
1- add attribute to the GridView
DataKeyNames="aboutusID"
2- add a templatefield to your columns
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="SelectSession" Text="EDIT" CommandArgument='<%# DataBinder.Eval(Container,"RowIndex")%>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
3- in your code behind
protected void GridViewAbout_RowCommand(object sender, GridViewCommandEventArgs e)
{
// this to skip on paging or sorting command
if (e.CommandName != "Sort" & e.CommandName != "Page")
{
// Get the command argument where the index of the clicked button is stored
int index = Convert.ToInt32(e.CommandArgument);
// Get the data key of the index where the id is stored
int id = Convert.ToInt32(GridViewAbout.DataKeys[index].Value);
if (e.CommandName == "SelectSession")
{
// Your Code
}
}
}
i think you should use the SelectedIndexChanged event for that.
Then you assign the GridviewRow property to the selected row "GridViewRow row = grdClients.SelectedRow;"
After that you can use row to get the value of the first cell and assign it to your session or where ever you want. "row.Cells[0].Text;"
protected void grdClients_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = grdClients.SelectedRow;
string id = row.Cells[0].Text;
Session["ID"] = id;
Response.Redirect("secondPage.aspx");
}
Thank you everyone,
I was able to come up with a solution by taking pieces from every solution you provided. Thanks very much.
Below is my solution:
protected void grdClients_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
string id = grdClients.Rows[index].Cells[0].Text.ToString();
Session["ID"] = id;
Response.Redirect("secondForm.aspx");
}
}
I hide my columns using the solution in following link
How to hide a TemplateField column in a GridView
However this causes problems with update operations, as gridview acts as hidden rows has null value. So how to hide columns after databind?
protected void begv_OrderDetail_RowCreated(object sender, GridViewRowEventArgs e)
{
((DataControlField)begv_OrderDetail.Columns.Cast<DataControlField>().Where(fld => fld.HeaderText == "FileNo").SingleOrDefault()).Visible = "False";
}
Try this,
grid1.Columns[columnIndex].Visible= false;
Edit based on comment of questioner, for getting values of hidden columns
You can use hidden fields to store column wise values. This article has example that will help how to use hidden fields.
Instead of hiding column you can put the data of columns in datakeynames and later access those values. This will be useful in grabbing how to use DataKeyNames. By this method you may need to pass the id from data key names and get the record.
try this example, (i don't speak english)
into RowDataBound ...
protected void gvTeste_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
teste listaTeste = e.Row.DataItem as ListaTeste;
if (listaTeste.ID == 0)
{
e.Row.Cells[2].Text = "Não Atribuido";
}
if (e.Row.Cells[7].Text == "01/01/0001" || e.Row.Cells[8].Text == "01/01/0001")
{
**e.Row.Visible = false;** // disable row
}
}
}
I have GridView with 2 columns.
The first column is: test-label (TemplateField)
The second: checkbox (asp:CheckBoxField) that connect to sql table with bit column (done).
I want that on page load - the page will check every row, where the checkbox = true, the test-label.visble will be false.
I know how to write code with SELECT statement to check the value from the SQL table, but don't know how to check every row on the gridview on the page-load.
how can I do that?
(i can't use findcontroll for the checkbox because it's checkboxfield and not just "checkbox".
<asp:CheckBoxField DataField="done" SortExpression="done" HeaderText="done?" />
so, what can I do here? maybe to replace that field with regular cb? (i don't know how to do there databind - on the regular cb).
you can use GridView.RowDataBound Event
so you can do something like
protected void GVRowDataBound(object sender, GridViewRowEventArgs e)
{
var check = (CheckBox) e.Row.FindControl("ID"); // ID is id of the checkbox
var lable = (Label) e.Row.FindControl("LableID");
if(check != null && lable != null)
{
if(check.Checked)
{
lable.Visible = false;
}
}
}
You can't do it in Page.Load because the GridView isn't databound yet.
Try handling GridView.RowDataBound.
Code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox cb = (CheckBox)e.Row.FindControl("checkbox");
Label lbl = (Label)e.Row.FindControl("test-label");
lbl.Visible = !(cb.Checked);
}
}
I want to Delete a row in the Gridview which is in the update panel . But instead of the command button ., i took a link button to get a confirmation message. Now if I press ok then the record should be deleted (both from db and frm girdview). I know how to delete from db but not when linkbutton is pressed, and deleting the record. And also the gridview is in update panel.so it should be reflected.
A sample code is appreciated.
Thanks
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
String productId = row.Cells[0].Text; // I suposed your product Id in very first column in gridview
//Delete Code goes here..........
...........................
}
}
you can use RowCommand event of gridview, like...
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
e.CommandArgument -- this return Data Key Value
//Deletion Code goes here.....
var brochureToDelete = (from b in dataContext.ArticleBrochures where b.ArticleId == ArticleId select b).FirstOrDefault();
if (brochureToDelete != null)
{
dataContext.ArticleBrochures.DeleteOnSubmit(brochureToDelete);
dataContext.SubmitChanges();
bindBrochureGridView(ArticleId);
// if your gridview in updatepanel
//Call update method of UpdatePanel
//UpdatePanel.Update();
}
}
Set PK_ID to link button's command args like that
<asp:LinkButton runat="server" ID="btn_manage" Text="Delete" CommandArgument='<%#Eval("PK_ID") %>'
OnCommand="btn_manage_click">
</asp:LinkButton>
and access this PK_ID on event
protected void btn_manage_click(object sender, CommandEventArgs e)
{
string ID = e.CommandArgument.ToString();
//you delete code and gridview bind code
}
bind the linkbutton id as the primary key. On client clicking the link button save that id in a hidden field. This hidden field value will be the id of row to be deleted.
Then on the server click of link button delete the row corresponding to the hidden field value
I presume you have a method which sends a delete query.
Make a RowDeleting event handler, pass your row index using e.RowIndex to the delete method.
Use this e.RowIndex to write a query to delete the 'n'th row of your table. and then bind the data to your gridView.