How to get the non visible gridview cell value in ASP.net? - asp.net

I have a grid like below.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" s
onrowcommand="GridView1_RowCommand">
<Columns>
<asp:ButtonField DataTextField="Name" HeaderText="Name" />
<asp:BoundField DataField="ArrDate" DataFormatString="{0:MM/dd/yyyy}"
HeaderText="Arr Date" />
<asp:BoundField HeaderText="Dep Date" DataField="DepDate"
DataFormatString="{0:MM/dd/yyyy}" />
<asp:BoundField HeaderText="Mail" DataField="Mail" />
<asp:BoundField HeaderText="Status" DataField="Status" />
<asp:BoundField DataField="ResId" HeaderText="ResId" Visible="False" />
</Columns>
</asp:GridView>
In Code Behind:-
try
{
string text = GridView1.Rows[2].Cells[5].Text;
ScriptManager.RegisterStartupScript(this, GetType(), "Message", "alert('ResId = " + text + ".');", true);
}
catch { }
Now the message shows - RegId =.
I can't get the value. So I change the RedId BoundField as vissible. Now I got the Value.
that is RegId =6.
I have two issue now -
1) How to get the RegId value in Non Visible Column.
2) How I find the Row value which i click... bzs the only i can change the ROWVALUE in code..
string text = GridView1.Rows[ROWVALUE].Cells[5].Text;

That is certainly not the right way to do it. You might want to look at using DataKeys to achieve this. With current approach, when you add a new column to your grid your code will fail.
Add your RegId column inside DataKeys property on your gridview
Reference your gridview datakey for the current row in codebehind like this
int regId= Convert.ToInt32(YourGridview.DataKeys[rowIndex]["RegId"].ToString());

Related

populate label with control id

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="audition_ID" DataSourceID="ObjectDataSource10" AllowPaging="True" AllowSorting="True">
<Columns>
<asp:BoundField DataField="audition_ID" HeaderText="audition_ID" InsertVisible="False" ReadOnly="True" SortExpression="audition_ID" />
<asp:BoundField DataField="audition_date" HeaderText="audition_date" SortExpression="audition_date" />
<asp:BoundField DataField="ins_ID" HeaderText="ins_ID" SortExpression="ins_ID" />
<asp:BoundField DataField="insturment_name" HeaderText="insturment_name" SortExpression="insturment_name" />
<asp:BoundField DataField="audition_status" HeaderText="audition_status" SortExpression="audition_status" />
<asp:BoundField DataField="audition_location" HeaderText="audition_location" SortExpression="audition_location" />
<asp:BoundField DataField="audition_time" HeaderText="audition_time" SortExpression="audition_time" />
<asp:HyperLinkField DataNavigateUrlFields="audition_ID" DataNavigateUrlFormatString="judgescores.aspx?auditionID={0}" HeaderText="Details" Text="Details" />
</Columns>
</asp:GridView>
I am using a grid view to display information for a database based on the selection in a drop down list. I have that working and when selecting the DDL- the grid view updates and shows the associated records.
I then added a "Details" hyperlink column that directs to the details.aspx page and picks up the ID so it shows the correct details associated with that record.
DataNavigateURLFormat = details.aspx?ID={0}
I can see the ID in the URL od this details page. What I am trying to do now is take that ID and populate it in a label on the details page.
I am exploring the "Expression" property in the Data section of the label properties- but have not found any luck using "AccessControlID" or "ClientIDMode" giving it a "RouteValue".
I was also exploring going in the code of the details page (details.aspx.vb)
and doing something like
lbldetail.Text = #ID
But not sure if that would work.
Any help would be greatly appreciated.
Contents of judgescores.aspx.vb page...
Partial Class Judges_judgescores
Inherits System.Web.UI.Page
Sub Page_Load()
lblCurrentAudition.Text = Request.QueryString[audition_ID]
End Sub

Programmatically Add ButtonColumn to GridView From DataTable

I have a problem adding a column with buttons in GridView.
As you see from the code below, the data source from teh GridView is a DataTable. I need to add an additional column to the table with a button.
From the code below, I get an error message saying:
Value of type 'System.Windows.Forms.DataGridViewButtonColumn' cannot
be converted to 'System.Web.UI.WebControls.DataControlField'.
Dim dt_AllGroupsSetUp2 As New DataTable()
dt_AllGroupsSetUp2.Columns.Add("Name", Type.GetType("System.String"))
dt_AllGroupsSetUp2.Columns.Add("Age", Type.GetType("System.String"))
dt_AllGroupsSetUp2.Columns.Add("Hight", Type.GetType("System.String"))
For i As Integer = 0 To 7
dt_AllGroupsSetUp2.Rows.Add()
dt_AllGroupsSetUp2.Rows(i)(0) = "John"
dt_AllGroupsSetUp2.Rows(i)(1) = 10
dt_AllGroupsSetUp2.Rows(i)(2) = 70
Next
GV_DataByGroupAct.DataSource = dt_AllGroupsSetUp2
Dim buttonColumn As New DataGridViewButtonColumn
buttonColumn.Name = "Button"
GV_DataByGroupAct.Columns.Add(buttonColumn)
GV_DataByGroupAct.DataBind()
I tried the folling also but returned the following error: 'New' cannot be used on a class that is declared 'MustInherit'.
GV_DataByGroupAct.DataSource = dt_AllGroupsSetUp2
Dim buttonColumn As New DataControlField
GV_DataByGroupAct.Columns.Add(buttonColumn)
GV_DataByGroupAct.DataBind()
Any ideas?
Thanks
In the code behind use this before binding data to GridView (but it's c#):
GV_DataByGroupAct.Columns.Add(new ButtonField() { Text = "Button" });
Or you could prepare the GridView with the button field
<asp:GridView ID="GV_DataByGroupAct" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" />
<asp:BoundField DataField="Hight" HeaderText="Hight" />
<asp:ButtonField Text="Button" />
</Columns>
</asp:GridView>
after bind you will have this result:
I was really complicating things. Thanks Jenda, it is easier to prepare the grid view. The following workds if it helps someone:
<asp:GridView ID="GV_DataByGroupAct" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" />
<asp:BoundField DataField="Hight" HeaderText="Hight" />
<asp:ButtonField Text="Button" />
</Columns>
</asp:GridView>
Code:
Dim dt_AllGroupsSetUp2 As New DataTable()
dt_AllGroupsSetUp2.Columns.Add("Name", Type.GetType("System.String"))
dt_AllGroupsSetUp2.Columns.Add("Age", Type.GetType("System.String"))
dt_AllGroupsSetUp2.Columns.Add("Hight", Type.GetType("System.String"))
For i As Integer = 0 To 7
dt_AllGroupsSetUp2.Rows.Add()
dt_AllGroupsSetUp2.Rows(i)(0) = "John"
dt_AllGroupsSetUp2.Rows(i)(1) = 10
dt_AllGroupsSetUp2.Rows(i)(2) = 70
Next
GV_DataByGroupAct.DataSource = dt_AllGroupsSetUp2
GV_DataByGroupAct.DataBind()
DataGridViewButtonColumn is intended to be used in DataGridView control.
With GridView you can use ButtonField.

Select a row without set AutoGenerateSelectButton to true

How to select a row without set AutoGenerateSelectButton to true and check selectedIndex in GridView_SelectedIndexChanged?
How to recognize that user select specific field on table (for example selected row2,col3)
This is an average gridview with no select button. The RowDataBound method makes your grid highlightable. You can check if a certain column was selected possibly with if conditions in your SelectedIndexChanged method as that will tell you what row was selected and then you can get a value from a specific column based on the order your columns were made as shown below. This wont show exactly where they clicked x and y but should head you in the right direction I think. This will however get column data based on what row was highlighted and clicked on with a post back of course.
<asp:GridView ID="PropertyGridView" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="PropertyGridView_SelectedIndexChanged" OnRowDataBound="PropertyGridView_RowDataBound">
<RowStyle HorizontalAlign="Left" />
<EmptyDataTemplate>
<div>
<asp:Label runat="server" ID="EtLbl" Text="No properties were found."</asp:Label>
</div>
</EmptyDataTemplate>
<Columns>
<asp:BoundField DataField="Name" HeaderText="User Name" Width="20%" /> </asp:BoundField>
<asp:BoundField DataField="Age" HeaderText="User Age" Width="20%" /> </asp:BoundField>
<asp:BoundField DataField="Height" HeaderText="User Height" Width="20%" /> </asp:BoundField>
</Columns>
</asp:GridView>
public void PropertyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItemIndex == -1)
return;
e.Row.Attributes.Add("onMouseOver", "this.style.cursor='hand';");
e.Row.Attributes.Add("onclick", this.GetPostBackClientEvent(PropertyGridView,"Select$" + e.Row.RowIndex.ToString()));
}
public void PropertyGridView_SelectedIndexChanged(object sender, EventArgs e)
{
string Name = PropertyGridView.SelectedRow.Cells[0].Text;
string Age= PropertyGridView.SelectedRow.Cells[1].Text;
string Height PropertyGridView.SelectedRow.Cells[2].Text;
if( Height != null)
{
// The user selected a row and this Column ( Height has data )
}
}
Add a column with a button (using a template field) and set the CommandName to "Select". That should work.

Copy GridView struture to another GridView

I have about 11 GridViews on my page: GridView1, GridView2, ... GridView10 and GridViewActive.
GridView1 to GridView10 are invisible, but GridViewActive is Visible.
Based on different conditions I need to copy structure of one GridView to GridViewActive.
I need to do something like
//common params
SqlDataSource1.SelectParameters["CommonParam1"].DefaultValue = this.commonParam1;
if (reportname = "report1")
{
SqlDataSource1.SelectParameters["Param"].DefaultValue = this.param;
CopyGridViewStructure(GridView1, GridViewActive);
}
else if (reportname = "report2")
{
SqlDataSource1.SelectParameters["AnotherParam"].DefaultValue = this.anotherParam;
CopyGridViewStructure(GridView2, GridViewActive);
}
etc.
// DO OTHER STAFF WITH GRIDVIEWATIVE HERE AND IN OTHER METHODS
And on button click (actually it is a bit more complicated than simple ButtonClick, as it is Ajax which calls Button click, and button is actually invisible for user):
//this block doesn't work for now, because grvActive doesn't have any structure
this.grvActive.DataSource = SqlDataSource1;
this.grvActive.DataBind();
I need to copy only Columns. Have not found sollution for this. GridView doesn't contain Clone method.
EDIT:
GridView1 to GridView10 and GridViewActive are not dynamically created.
Example of GridView:
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" Visible="false">
<Columns>
<asp:BoundField DataField="username" HeaderText="First Name">
<ItemStyle Width="110px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="usersurname" HeaderText="Last Name">
<ItemStyle Width="110"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="usertype" HeaderText="User Type">
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Login">
<ItemTemplate>
<asp:Label runat="server" ID="lblLastModifyDate" Text='<%# MyUtility.MyCommon.FormatDate(Eval("logindate").ToString()) %>' />
</ItemTemplate>
<ItemStyle Width="177px"></ItemStyle>
</asp:TemplateField>
</Columns>
</asp:GridView>
Other GridView are very similar, but with different columnnames and datafields. Some of them contains different TemplateField, some doesn't have TemplateFields at all.
I have not found a sollution for copying GridView structure, however, I have found a solution for my problem. Instead of Cloning structure, I am saving GridView ID and then I am using FindControl.
private string GridID
{
get
{
return ViewState["GridID "].ToString();
}
set
{
ViewState["GridID "] = value;
}
}
And then
SqlDataSource1.SelectParameters["CommonParam1"].DefaultValue = this.commonParam1;
if (reportname = "report1")
{
SqlDataSource1.SelectParameters["Param"].DefaultValue = this.param;
// //CopyGridViewStructure(GridView1, GridViewActive);
GridID = "GridView1";
}
else if (reportname = "report2")
{
SqlDataSource1.SelectParameters["AnotherParam"].DefaultValue = this.anotherParam;
CopyGridViewStructure(GridView2, GridViewActive);
GridID = "GridView2";
}
etc.
And when I need to use gridView, I am using FindControl:
GridView grd = (GridView) this.FindControl(GridID);
// actually for my page I am using masterpage and FindControl is a bit more complicated:
GridView grd = (GridView)((ContentPlaceHolder)(this.Controls[0].FindControl("mainContent"))).FindControl(GridID);
I found some solution:
In Source aspx after grid databind:
Session["gridtoexcel"] = yourgrid;
In destination aspx
var grid = ((GridView)Session["gridtoexcel"]);
gridToExcel.Columns.Clear();
foreach (DataControlField col in grid.Columns)
gridToExcel.Columns.Add(col);
gridToExcel.DataSource = grid.DataSource;
gridToExcel.DataBind();
this way i can 'clone' exact grid to another page.
if you need some css style don't forget of add them in destination page

Calling Data From GridView

I have a GridView with a bunch of DynamicFields like so;
<asp:GridView ID="GridView1" runat="server" DataSourceID="GridDataSource">
<Columns>
<asp:DynamicField HeaderText="Date Submitted" DataField="DATE_CREATED" />
<asp:DynamicField HeaderText="Assigned To" DataField="ASSIGNED_TO" />
<asp:DynamicField HeaderText="Active Account" DataField="Active_Account" />
<asp:DynamicField HeaderText="Client ID" DataField="CLIENT_ID" />
<asp:DynamicField HeaderText="Client Type" DataField="CLIENT_Type" />
</Columns>
</asp:GridView>
<asp:EntityDataSource ID="GridDataSource" OnSelected="TotalRows" runat="server"
EnableDelete="true">
<WhereParameters>
<asp:DynamicControlParameter ControlID="FilterRepeater" />
</WhereParameters>
</asp:EntityDataSource>
Now it displays fine, the right data comes to screen but when I try to access that data using a row number I'm always finding blank cells. For example I tried the following to check every cell but to no avail;
Dim x As Integer = 0
Dim y As Integer = 0
While x < GridView1.Rows.Count
While y < GridView1.Rows(x).Cells.Count
If Not (GridView1.Rows(x).Cells(y).Text = "") Then
MsgBox(String.Format("{0},{1},{2}", x.ToString, y.ToString,
GridView1.Rows(x).Cells(y).Text))
End If
y = y + 1
End While
x = x + 1
y = 0
End While
No message box displayed so all the cells are empty strings. But I can clearly see they're populated on screen! What am I doing wrong?
UPDATE
After Pilgerstorfer Franz suggestion that I look for Textbox elements I used the following code which basically looks at all the cells in the table and try's to pull data out of them and if it's not blank then display a msgbox (also informs me of any new controls I haven't accounted for);
If GridView1.Rows(0).RowType = DataControlRowType.DataRow Then
For r = 0 To GridView1.Rows.Count - 1
For c = 0 To (GridView1.Rows(r).Cells.Count - 1)
Dim cell = GridView1.Rows(r).Cells(c)
For b = 0 To cell.Controls.Count - 1
If (cell.Controls(b).GetType() Is GetType(TextBox)) Then
Dim td = CType(cell.Controls(b), TextBox)
Text = td.Text.Trim
ElseIf (cell.Controls(b).GetType() Is GetType(LiteralControl)) Then
Dim td = CType(cell.Controls(b), LiteralControl)
Text = td.Text.Trim
ElseIf (cell.Controls(b).GetType() Is GetType(DynamicControl)) Then
Dim td = CType(cell.Controls(b), DynamicControl)
Text = td.Table.Columns.Item(c).DisplayName()
Else
MsgBox(String.Format("New Control of type: {0}", cell.Controls(b).GetType().FullName))
End If
If Not Text = "" Then
MsgBox(String.Format("{0},{1},{2}", c.ToString, b.ToString, Text))
End If
Next
Next
Next
End If
Unfortunately most cells just contained DynamicControl and since I was putting the DisplayName into Text I was just getting the column header every time. So how do I get the text value property out of a DynamicControl?
Additional Info
I'm further confused by this problem because since this is a project that I'm updating there is initial code two lines of which are;
Dim UserID = Convert.ToInt32(GridView1.DataKeys(e.RowIndex).Value)
Dim clientType As String = GridView1.DataKeys(e.RowIndex).Item(1).ToString
These successfully bring back UserID and ClientType. Now I don't really understand DataKeys but I tried using;
Dim clientType As String = GridView1.DataKeys(e.RowIndex).Item(Num).ToString
where Num increases by one every time expecting it to bring back the rest of the row data, but I simply got an index was out of range error.
ANOTHER UPDATE!!
Here is another bit of the ASPX page but I'n not entirely certain what it does. Pilgerstorfer Franz created some code to look for the textboxes created by the dynamicControl. Now I'm wondering if this code here causes other types of controls to be used rather than Textboxes. Thoughts?
<asp:FilterRepeater ID="FilterRepeater" runat="server" Visible="false">
<ItemTemplate>
<h2><asp:Label ID="lblDisplay" runat="server" Text='<%#
Eval("DisplayName") %>' AssociatedControlID="DynamicFilter$DropDownList1" /></h2>
<asp:DynamicFilter runat="server" ID="DynamicFilter"
OnSelectedIndexChanged="OnFilterSelectedIndexChanged" />
</ItemTemplate>
<FooterTemplate><br /><br /></FooterTemplate>
</asp:FilterRepeater>
According to my assumptions (see comments) I did a small demo...
<asp:DynamicDataManager ID="DynamicDataManager1" runat="server">
<DataControls>
<asp:DataControlReference ControlID="GridView1" />
</DataControls>
</asp:DynamicDataManager>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ContactID" DataSourceID="EntityDataSource1" AllowPaging="true"
OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:DynamicField DataField="ContactID" ReadOnly="true" HeaderText="ContactID" />
<asp:DynamicField DataField="Title" HeaderText="Title" />
<asp:DynamicField DataField="FirstName" HeaderText="FirstName" />
<asp:DynamicField DataField="LastName" HeaderText="LastName" />
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
<asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=dbTestIT34_EFEntities"
DefaultContainerName="dbTestIT34_EFEntities" EnableFlattening="False" EnableUpdate="True"
EntitySetName="Contacts" EntityTypeFilter="Contact">
</asp:EntityDataSource>
And according to my data storage I did handle the rowUpdating event. Unfortunatelly accessing any control within a dynamic control is not easy. So I did a very quick and dirty hack...
protected void Page_Init(object sender, EventArgs e)
{
GridView1.EnableDynamicData(typeof(Contact));
EntityDataSource1.ContextType = typeof(dbTestIT34_EFEntities);
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int row = 0;
int firstNameColumn = 2;
while (row < GridView1.Rows.Count)
{
// sorry, a little bit confusing ...
// as dynamic control generates other controls dynamically,
// this was the very first thing that worked for me!
TextBox t = GridView1.Rows[row].Cells[firstNameColumn].Controls[0].Controls[0].Controls[0] as TextBox;
if (t != null)
Debug.WriteLine(t.Text);
row++;
}
}
Hope that helps!
Iterating through the controls never worked for me so in the end I gave up and just queried the DB again... Eh it works.

Resources