Cannot find id of control inside gridview which inside another gridview - asp.net

Can anyone help me on this?
I have a button(ImageButton1) inside a GridView (gvSdt), and gridview b is inside another Gridview (gvClass).
but it come out an error said "The name 'gvSdt' does not exist in the current context"
The code i used as below:
protected void gvSdt_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = gvSdt.SelectedRow;
int rowIndex = gvSdt.SelectedIndex;
string strValue = gvSdt.DataKeys[rowIndex].Value.ToString();
}

Since gvSdt is contained within another GridView, you won't be able to access it directly, as it is repeated content. Since gvSdt can exist multiple times, gvSdt would therefore refer to multiple GridViews.
This is made easy however, since you are using the SelectedIndexChanged event of the GridView in question. Notice the sender argument of the method. The object that gets passed there is actually the GridView. So just cast it as such.
protected void gvSdt_SelectedIndexChanged(object sender, EventArgs e)
{
GridView gvSdt = (GridView)sender;
GridViewRow row = gvSdt.SelectedRow;
int rowIndex = gvSdt.SelectedIndex;
string strValue = gvSdt.DataKeys[rowIndex].Value.ToString();
}

Related

How to edit gridview row inside?

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.

Sorting a gridview using a datatable, and datasource that is an ArrayList

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx
This article deals with creating a datatable first, then creating a gridview from it, to aid in sorting. My predicament is slightly different.
I have a Gridview, that on Page_Load, I set the datasource to an ArrayList, and bind.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.GridView1.DataSource = RequestManager.Instance.GetAllRequests();
this.GridView1.DataBind();
}
}
Now I would like to sort this GridView, so on the aspx page, I set AllowSorting="true", and OnSorting="GridView1_Sorting". So far, so good. I have the SortExpressions set in the BoundFields, and when I click on it, I know the _Sorting event is triggered.
Now, since this is a postback operation, I cannot simply cast the datasource of the gridview to a DataTable to sort. Saving to ViewState is an option, but I cannot figure out how to do it.
I would like to use the simple solution on this page, except for the DataTable not being available to me. Thanks for looking.
If you're able to target .NET v3.5, I recommend using Linq. In your _Sorting event handler, get the array list you did in the Page_Load and rebind it.
For example, if the type contained in the array list are MyType instances that have properties named Default and SomeField:
protected void Grid_Sorting(object sender, GridViewSortEventArgs e)
{
Func<MyType, object> keySelector;
if(e.SortExpresion == "SomeField")
{
keySelector = dataItem => dataItem.SomeField;
}
else
{
keySelector = dataItem => dataItem.Default;
}
ArrayList dataItems = RequestManager.Instance.GetAllRequests();
this.GridView1.DataSource = dataItems.OfType<MyType>().OrderBy(keySelector);
this.GridView1.DataBind();
}
That will get you started, then later inspect the sort expression to see if it ends with ASC or DESC and conditionally call .OrderByDescending(keySelector).
Finally, I don't recommend stashing the list in ViewState, as the ObjectStateFormatter is only optimized for a handful of types. http://msdn.microsoft.com/en-us/library/system.web.ui.objectstateformatter.aspx
Maybe consider ASP.NET cache instead.

Assigning a session variable into DetailsView

I have a Session Variable declared and checked that it exists. I would like the DetailsView to display the Session Variable number in the INSERT Textbox in the DetailsView. When the Insert Button is pressed I, require the record in the DetailsView to be despatched to the database, to create an additional record.
From the experimentation I have carried out, it appears to be difficult to penetrate the DetailsView. I imagine that there is a requirement for some "Code Behind" to be included.
You need to use the detailsview Databound event and assign the value to the textbox. e.g.
protected void DetailsView1_DataBound(object sender, EventArgs e)
{
if (DetailsView1.CurrentMode == DetailsViewMode.Insert)
{
TextBox TextBox1 = DetailsView1.FindControl("TextBox1") as TextBox;
TextBox1.Text = Session["Name"].ToString();
}
}

How can I get selected row cell value of grid view on page?

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);
................
}
}

How do I get the TotalRowCount from a LinqDataSource into a Literal?

I have a LinqDataSource that I use to calculate the number of rows in a table. I would like to update the value of literal with the number, with the following code, taken from MSDN (linqdatasourcestatuseventargs.totalrowcount.aspx):
protected void linqDataSource1_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
Literal1.Text = e.TotalRowCount.ToString();
}
By how do I trigger the select event on the data source? The SqlDataSource class has a Select() method so that it can be triggered programmatically in e.g. Page_Load, but the LinqDataSource does not have this method. I currently solved the problem by binding my data source to an empty FormView element, but this is just too ugly.
I feel pretty confident that there is a much nicer way to get the total number of rows into my literal when using LinqToSql, I just don't know how to do so.
The suggestion by tvanfosson, of attaching an method to the data source's selected event, does unfortunately not solve my problem, because the select event is still not triggered when the page loads. (I have, by the way, already attached the _Selected method with the OnSelected attribute, like this)
<asp:LinqDataSource ID="linqDataSource1" runat="server"
OnSelected="linqDataSource1_Selected">
Hook up your method as an event handler for the Selected event in Page_Load.
public void Page_Load( object sender, EventArgs e )
{
linqDataSource1.Selected += LinqDataSource1_Selected;
}
protected void LinqDataSource1_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
Literal1.Text = e.TotalRowCount.ToString();
}
I ended up dropping the data source and instead put the code in the code behind. Not really the point-and-click-programming that I was going for, but still quite short. I looks something like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var context = new MyDataContext();
numberOfModificationsLiteral.Text =
(
from modification in context.Modifications
where modification.Start >= DateTime.Now
select modification
).Count().ToString();
}
}

Resources