I want to edit row of gridview.For that, I have added showeditbutton = true.I have binded gridview from cs file.Does I need to wite 3 function for that?(For editing I have added 3 function in cs file.).I have taken help from internet.But some point did not understand.
--In aspx
<asp:GridView datakeyname="Id" Id ="Gridview1" onRowEditing="GridView1_RowEditing" RowCancelingEdit=" GridView1_RowCancelingEdit" onRowUpdating ="GridView1_RowUpdating" >
<column>
// hyperlink ,dataTextfield is id
// some checkboxfield.(start from column 6)
</column>
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
//code for Binding grid
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// for fetching value of id and checkboxfield(column 6)
string Id= GridView1.DataKeys[e.RowIndex].Values["Id"].ToString());
bool ischeck = (Gridview1.Rows[e.RowIndex].Cells[5].Controls[0] as checkBox).Checked;
// code for updating grid
GridView1.EditIndex = -1;
//Now bind the gridview gain here
}
protected void GridView1_RowCancelingEdit(object sender, GridViewUpdateEventArgs e)
{
GridView1.EditIndex = -1;
//Now bind the gridview gain here
}
Does am I going in right direction?What is use of datakey.Does I used properly?Why GridView1.EditIndex = -1 in update and cancel event.Column 6 is checkboxfield.why .Controls[0] is used for accessing that checkboxfield.
If you are using an ObjectDataSource (or SqlDataSource or OleDbDataSource) to databind and use UpdateCommand, DeleteCommand, InsertCommand, then you do not need to explicitly write those three functions for the edit/update operation. You need those functions when you are writing the binding code in code-behind or if you want to do additional work before/after any operation.
RowEditing fires when you click "edit" on the GridView. Here you specify what row to open in editmode by writing GridView1.EditIndex = e.NewEditIndex. You can also write code here to do any work that is required before user is put into editmode. For example, you can check for business rules conditions, and cancel the operation if rules are not met.
RowUpdating fires when you click "save"/"update" on the GridView. This is fired before the actual database operation. If you have an UpdateCommand on the datasource, then you do not need to write database save routine, otherwise you write that here.
DataKeys identify the "key" that identifies the data that is bound. You specify DataKeys while databinding to the GridView. For example, primary key of a database table. This line: string Id= GridView1.DataKeys[e.RowIndex].Values["Id"].ToString()); Here you are picking up the value of the "Id" key (you can have more than one keys) of the current row.
GridView1.EditIndex = -1 in update or cancel specifies that the GridView should no longer be in editmode. If this value is >= 0, then the GridView is put into editmode for that row (index starting from 0). So we set it to -1, to indicate that it should not be in editmode.
Controls[0] is used to pick the first control in that cell (you may have more than one controls). Alternatively, you can also use FindControl.
I have a GridView that gets it's data from the SQL database.
I would like to alter some of it using an external method, something like this:
SQL in:
ID:0
Then, the altered method will be called with 0 as a parameter, and will return some string that will be shows in the GridView.
Thank you, Mark.
Attach a handler to the RowDataBound event. You have full control to all of the cells in the GridViewRow, and can modify the text anyway you want. Example from MSDN:
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Display the company name in italics.
e.Row.Cells[1].Text = "<i>" + e.Row.Cells[1].Text + "</i>";
}
}
Reference at: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx
i have a gridview in web page
<asp:GridView ID="grid_search" runat="server" >
and it contains Footer for total value of Columns
i have a Column name Production value in Gridview
prod_val nvarchar(50)
for data bind i use the code behind
protected void grid_search_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
`tot_prodVal = tot_prodVal + Convert.ToDecimal(e.Row.Cells[2].Text);`
}
}
but it shows an error at debugging time that
System.FormatException: Input string was not in a correct format.
plz give me solution..
Since you have mentioned footer in your question, I am guessing you want to perform that operation in the footer. So your if condition should be
e.Row.RowType == DataControlRowType.Footer
I guess because you are using DataRow in your condition, e.Row.Cells[2].Text doesn't really point to the field you want it to.
I am using a Grid View on my page.
I want to show the data of the selected row cell through response.write(), on the click event of the page button.
Note::
please set the CommandName of your
button to "selectCol"
Please set the CommandName for the
second button , you will use to
delete
to"deleteCol"
Set the command argument property for your button :
.aspx
CommandArgument='<%#((GridViewRow)Container).RowIndex%>'
CommandArgument='<%#((GridViewRow)Container).RowIndex%>'
for the two buttons.
.cs
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "selectCol")
{
Response.Write(gv.Rows[index].Cells[0].Text); //consider you use bound field and the column you want to show its value is the first column.
}
else if(e.CommandName == "deleteCol")
{
int id = int.Parse(gv.DataKeys[index].Value.ToString());//the primary key for your table.
Delete(id);//method which use (Delete From .... Where id = ....).
}
gv.DataBind();
}
catch (Exception ee)
{
string message = ee.Message;
}
}
Greeting Hims.
Easyest way to read value from gridview field is to write:
your_grid_name.SelectedRow.Cell(*number_of_index*).text
In my case that is:
Dim employer_name As String
employer_name=poslodavac_grid.SelectedRow.Cells(1).Text
Just remember that first cell index is zero and that doesn't count "asp:CommandField ShowSelectButton" tag as first one ...
Use GridView.SelectedRow property.
String cellText = this.gridView.SelectedRow.Cells[cellIndex].Text;
Refer to the following to learn about selecting a row in a GridView control.
Select Command in a GridView Control in ASP.Net
If you are using a LINK BUTTON in your grid view, you can use the following code in the ROWCOMMAND method. This code with retrieve all the values in the particular selected row.
// to get the value of the link use the command argument
FaultId = Convert.ToInt32(e.CommandArgument);
// to get the other column values
UserId = Convert.ToInt32(((GridViewRow(((LinkButton)e.CommandSource).NamingContainer)).Cells[1].Text);
Department = ((GridViewRow(((LinkButton)e.CommandSource).NamingContainer)).Cells[2].Text;
ProblemType = ((GridViewRow)(((LinkButton)e.CommandSource).NamingContainer)).Cells[3].Text;
You can get it in the RowCommand event of the gridview:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
Response.Write(row.Cells[0].Text);
Response.Write(row.Cells[1].Text);
................
}
}
GridView1.Columns.Count is always zero even SqlDataSource1.DataBind();
But Grid is ok
I can do
for (int i = 0; i < GridView1.HeaderRow.Cells.Count;i++)
I rename request headers here
but
GridView1.Columns[i].Visible = false;
I can't use it because of GridView1.Columns.Count is 0.
So how can I hide them ?
Try putting the e.Row.Cells[0].Visible = false; inside the RowCreated event of your grid.
protected void bla_RowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Visible = false; // hides the first column
}
This way it auto-hides the whole column.
You don't have access to the generated columns through grid.Columns[i] in your gridview's DataBound event.
The Columns collection is only populated when AutoGenerateColumns=false, and you manually generate the columns yourself.
A nice work-around for this is to dynamically populate the Columns collection yourself, before setting the DataSource property and calling DataBind().
I have a function that manually adds the columns based on the contents of the DataTable that I want to display. Once I have done that (and then set the DataSource and called DataBind(), I can use the Columns collection and the Count value is correct, and I can turn the column visibility on and off as I initially wanted to.
static void AddColumnsToGridView(GridView gv, DataTable table)
{
foreach (DataColumn column in table.Columns)
{
BoundField field = new BoundField();
field.DataField = column.ColumnName;
field.HeaderText = column.ColumnName;
gv.Columns.Add(field);
}
}
Note: This solution only works if your GridView columns are known ahead of time.
It sounds like you're using a GridView with AutoGenerateColumns=true, which is the default. I recommend setting AutoGenerateColumns=false and adding the columns manually:
<asp:GridView runat="server" ID="MyGridView"
AutoGenerateColumns="false" DataSourceID="MySqlDataSource">
<Columns>
<asp:BoundField DataField="Column1" />
<asp:BoundField DataField="Column2" />
<asp:BoundField DataField="Column3" />
</Columns>
</asp:GridView>
And only include a BoundField for each field that you want to be displayed. This will give you the most flexibility in terms of how the data gets displayed.
I was having the same problem - need my GridView control's AutogenerateColumns to be 'true', due to it being bound by a SQL datasource, and thus I needed to hide some columns which must not be displayed in the GridView control.
The way to accomplish this is to add some code to your GridView's '_RowDataBound' event, such as this (let's assume your GridView's ID is = 'MyGridView'):
protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[<index_of_cell>].Visible = false;
}
}
That'll do the trick just fine ;-)
You have to perform the GridView1.Columns[i].Visible = false; after the grid has been databound.
Try this to hide columns in an ASP.NET GridView with auto-generated columns, both RowDataBound/RowCreated work too.
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Or _
e.Row.RowType = DataControlRowType.Header Then // apply to datarow and header
e.Row.Cells(e.Row.Cells.Count - 1).Visible = False // last column
e.Row.Cells(0).Visible = False // first column
End If
End Sub
Protected Sub GridView1_RowCreated(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowCreated
If e.Row.RowType = DataControlRowType.DataRow Or _
e.Row.RowType = DataControlRowType.Header Then
e.Row.Cells(e.Row.Cells.Count - 1).Visible = False
e.Row.Cells(0).Visible = False
End If
End Sub
In the rowdatabound method for 2nd column
GridView gv = (sender as GridView);
gv.HeaderRow.Cells[2].Visible = false;
e.Row.Cells[2].Visible = false;
#nCdy:
index_of_cell should be replaced by an integer, corresponding to the index number of the cell that you wish to hide in the .Cells collection.
For example, suppose that your GridView presents the following columns:
CONTACT NAME | CONTACT NUMBER | CUSTOMERID | ADDRESS LINE 1 | POST CODE
And you want the CUSTOMERID column not to be displayed.
Since collections indexes are 0-based, your CUSTOMERID column's index is..........? That's right, 2!! Very good.
Now... guess what you should put in there, to replace 'index_of_cell'??
As said by others, RowDataBound or RowCreated event should work but if you want to avoid events declaration and put the whole code just below DataBind function call, you can do the following:
GridView1.DataBind()
If GridView1.Rows.Count > 0 Then
GridView1.HeaderRow.Cells(0).Visible = False
For i As Integer = 0 To GridView1.Rows.Count - 1
GridView1.Rows(i).Cells(0).Visible = False
Next
End If
I found Steve Hibbert's response to be very helpful. The problem the OP seemed to be describing is that of an AutoGeneratedColumns on a GridView.
In this instance you can set which columns will be "visible" and which will be hidden when you bind a data table in the code behind.
For example:
A Gridview is on the page as follows.
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False" >
</asp:GridView>
And then in the code behind a PopulateGridView routine is called during the page load event.
protected void PopulateGridView()
{
DataTable dt = GetDataSource();
gv.DataSource = dt;
foreach (DataColumn col in dt.Columns)
{
BoundField field = new BoundField();
field.DataField = col.ColumnName;
field.HeaderText = col.ColumnName;
if (col.ColumnName.EndsWith("ID"))
{
field.Visible = false;
}
gv.Columns.Add(field);
}
gv.DataBind();
}
In the above the GridView AutoGenerateColumns is set to False and the codebehind is used to create the bound fields. One is obtaining the datasource as a datatable through one's own process which here I labeled GetDataSource(). Then one loops through the columns collection of the datatable. If the column name meets a given criteria, you can set the bound field visible property accordingly. Then you bind the data to the gridview. This is very similar to AutoGenerateColumns="True" but you get to have criteria for the columns. This approach is most useful when the criteria for hiding and un-hiding is based upon the column name.
Similar to accepted answer but allows use of ColumnNames and binds to RowDataBound().
Dictionary<string, int> _headerIndiciesForAbcGridView = null;
protected void abcGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (_headerIndiciesForAbcGridView == null) // builds once per http request
{
int index = 0;
_headerIndiciesForAbcGridView = ((Table)((GridView)sender).Controls[0]).Rows[0].Cells
.Cast<TableCell>()
.ToDictionary(c => c.Text, c => index++);
}
e.Row.Cells[_headerIndiciesForAbcGridView["theColumnName"]].Visible = false;
}
Not sure if it works with RowCreated().
Iterate through the GridView rows and make the cells of your target columns invisible. In this example I want to keeps columns 4-6 visible as is, so we skip those:
foreach (GridViewRow row in yourGridView.Rows)
{
for (int i = 0; i < rows.Cells.Count; i++)
{
switch (i)
{
case 4:
case 5:
case 6:
continue;
}
row.Cells[i].Visible = false;
};
};
Then you will need to remove the column headers separately (keep in mind that removing header cells changes the length of the GridView after each removal):
grdReportRole.HeaderRow.Cells.RemoveAt(0);