problem with the nested gridview - c#

I'm trying add a gridview dynamically (lets call this gridview2) to existing gridview (lets call this gridview1) added through .aspx page.
What i'm trying to do is: Depending upon the content of the row (more specifically invoice number displayed in the cell-1 with zero based indexing) displayed in "gridview1" i'm filtering data from a list and displaying the data in "gridview2".
I'm doing some terrible mistake somewhere or my approach should be fundamentally wrong.
Below is the code for gridview1 added in .aspx page.
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="ClickingBtn_Click" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="Date Of Transaction"
HeaderText="Date Of Transaction" SortExpression="Date Of Transaction" />
<asp:BoundField DataField="Invoice Number" HeaderText="Invoice Number"
SortExpression="Invoice Number" />
<asp:BoundField DataField="totalAmount" HeaderText="totalAmount"
ReadOnly="True" SortExpression="totalAmount" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ComponentDBConnectionString %>"
SelectCommand="SelectUserPreviousHistory" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="duran" Name="userName" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
This is fetching the data as shown here: here
And then I'm trying to add another gridview depending upon the unique invoice number displayed in each row by following code:
foreach (GridViewRow gridviewrow in GridView1.Rows)
{
GridView gridView2 = new GridView();
gridView2.AutoGenerateColumns = true;
String x = gridviewrow.Cells[1].Text; //IT FETCHES THE INVOICE NUMBER FROM EACH ROW
softwareTitlesList = SoftwareListRetrieve(); //lIST OF ALL THE SOFTWARE TITLES ADDED TO LIST
ArrayList titles = new ArrayList();
foreach (SoftwareTitles softwareTitle in softwareTitlesList)
{
if (softwareTitle.InvoiceNumber.Contains(x))
titles.Add(softwareTitle.SoftwareTitle); //ADDING ONLY THOSE TITLES THAT MATCH THAT PARTICULAR INVOICE NUMBER
}
gridView2.DataSource = titles;
gridView2.DataBind();
}
But nothing seems to be happening. What is wrong with this ?
Please help me
BTW I'm using asp.net/c# visualstudio 2010. And i'm not using LINQ in my project and the database is sql server 2005
Thanks in anticipation

There are quite a few problems with your approach.
You do create a new gridview in your server side code but you never add the gridview to the page or any other control on the page! It is effectively telling the .NET to create a gridview, bind it to the data but it is not telling .NET "where" to render the gridview on the page. Hence you don't see anything.
Dynamic controls - I am sorry if I am being presumptuous here but I think you haven't had much play with dynamic controls within ASP.NET. My whole hearted advice will be to not use them as far as you can. Dynamically created controls come with a HUGE baggage with respect to their state, their post back events and actually have to be added on every post back to the page. In a nutshell, if you add a button dynamically on the page as
Button btn = new Button();
btn.Text = "hi";
Page.Controls.Add(btn);
Then you must fire this code on every postback of the page. If during any postback this code doesn't get fired, the button will be missing when the client sees the page.
I can suggest some approaches to achieve what you are trying to do, however to be able to do that I would like to know
Where do you want the second gridview to appear in the page (i.e. embedded within the first one or outside of it)
When do you want to populate the second gridview? Is it something like the situation that the user clicks one row in the first gridview and then sees the relevant information in the second gridview?

Related

ASP.NET DataGrid is empty

I have a ASP.NET datagrid which is on a user control. I have a main page which adds the user control ( sometimes multiple copies of the user control ) and restores them when a post back occurs.
The dataGrid has insert / edit / delete links. I can add multiple copies of the user control to the page and the insert / edit delete functionality works perfectly for each separate control.
Yesterday I added some property binding to the main page to which are unrelated to the user control using the format Text='<%# DocumentTitle %>'. Initially I couldn't get this to work until I added Page.DataBind(); to the main page's Page_Load method. At this point the property binding started working correctly but then I noticed the insert functionality had stopped working in the datagrid within each user control....I debugged and found that when the following line executes it finds the text fields in the controls within the dataGrid to be empty or "":
eInfo.Ref = ((TextBox)gvEG.FooterRow.FindControl("txtEmployeeName")).Text;
If I remove the page.DataBind() method from the main page then the property binding stops working but the dataGrid(s) in the userControl start working.
My question is two fold i) Why does the seemingly unrelated change effect the dataGrid and ii) what do I do to get this working?
I've added the relevant sections of my code below...or at least what I think are the relevant sections.
Default.aspx
<div class="general">
<asp:TextBox Width="488" runat="server" placeholder="Document Title" Text='<%# DocumentTitle %>'></asp:TextBox>
</div>
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Create an empty user control for the first requirements section.
EmployeeSectionUserControl myUserControl1 = (EmployeeSectionUserControl )LoadControl("~/EmployeeSectionUserControl .ascx");
// Add it to the panel control holding all the user controls.
MainPanel.Controls.Add(myUserControl1);
DocumentTitle = "I am the default document title and I'm bound.";
}
else
{
// Do nothing
}
Page.DataBind();
}
EmployeeSectionUserControl.ascx
<asp:GridView ID="gvEG" runat="server" AutoGenerateColumns="False" CssClass="grid"
AlternatingRowStyle-CssClass="gridAltRow" RowStyle-CssClass="gridRow" ShowFooter="True"
EditRowStyle-CssClass="gridEditRow" FooterStyle-CssClass="gridFooterRow" OnRowCancelingEdit="gvEG_RowCancelingEdit"
OnRowCommand="gvEG_RowCommand" OnRowDataBound="gvEG_RowDataBound" OnRowDeleting="gvEG_RowDeleting"
OnRowEditing="gvEG_RowEditing" OnRowUpdating="gvEG_RowUpdating" DataKeyNames="Id" ShowHeaderWhenEmpty="true">
<Columns>
<asp:TemplateField HeaderText="Id" HeaderStyle-HorizontalAlign="Left" ControlStyle-Width="50px">
<ItemTemplate>
<%# Eval("Id")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Ref" HeaderStyle-HorizontalAlign="Left" ControlStyle-Width="90px">
<EditItemTemplate>
<asp:TextBox ID="txtEmployeeName" runat="server" Text='<%# Bind("Ref") %>'
Width="90px"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmployeeName" runat="server" Width="90px"></asp:TextBox>
</FooterTemplate>
EmployeeSectionUserControl.ascx.cs
protected void gvEG_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
employeeInfo eInfo = new employeeInfo();
eInfo.Id = 999;// Convert.ToInt32(((TextBox)gvEG.FooterRow.FindControl("Id")).Text);
// If we're inserting from the EmptyDataTemplate( ie an empty table ) of the gridview then we need to retreive the data differently.
// So we perform a check on the gridView FooterRow and if it's null then we can assume it's an empty table.
if (gvEG.FooterRow == null)
{
TextBox referenceTxtBox = (((Control)e.CommandSource).NamingContainer).FindControl("txtEmployeeName") as TextBox;
eInfo.Ref = referenceTxtBox.Text;
}
else
{
eInfo.Ref = ((TextBox)gvEG.FooterRow.FindControl("txtEmployeeName")).Text;
eInfo.Need =
}
// Store Update and Re-bind data to grid.
}
}
Page.DataBind() calls DataBind on it's children, so it updates DocumentTitle in the text box but it also DataBinds your grid. I didn't see a DataSource set in your grid, like an EntityDataSource, so I am assuming you are doing the smart retrieving (and preparation) of the data yourself in code and set the DataSource yourself:
gvEg.DataSource = someCollection;
gvEg.DataBind();
On the get your are loading the user-control and probably call this DataBind with specifying the DataSource. It binds and then you call Page.DataBind() which probably also triggers another DataBind for gvEg but since DataSource is set it shows the same.
On the post back you shouldn't do a DataBind() before handling events. Your call of Page.DataBind() does that. It triggers a DataBind() without a DataSource. Then the rowCommand comes and checks for the TextBox in the Footer which is cleared due to a DataBind with no elements.
What you should do is:
You shouldn't use Page.DataBind(). If you do so, you need todo it at a moment when all DataSources are set correctly and it shouldn't be kicked of during a post back. In general, I would not recommend using it because it makes it more complex and it's probably only helping a bit if you haven't set up your application correctly.
In your case it's definitely not necessary. Your textBox is a server control that's not part of any binding (GridView, Repeater, ListView). So your textBox is immediately available in your code behind.
So you should:
Give the textBox an ID you can use like txtDocumentTitle
<asp:TextBox Width="488" ID="txtDocumentTitle" runat="server" placeholder="Document Title"></asp:TextBox>
Replace setting DocumentTitle (unless you need it for something else too) with:
txtDocumentTitle.Text = "I am the default document title and I'm bound.";
Remove Page.DataBind();
So access server controls you have access immediately since they are also properties in your page or control.

Hyperlink in Gridview which is autogenerated in C#

I have a Gridview which is autogenerated by fetching data from various tables.
Now my requirement is i need to make my first column as hyperlink so that if it is clicked then it has to navigate to another page with hyperlinked value.
In the second page i have Lable this label should show the hyperlink value and based on that the data will be populated on the second page.
For example:
I have a gridview with 10 columns..My first column is Emp Id.
If that id is clicked it has to take me to second page and the label control must get this id value and based on that id the rest of the info like emp name emp DOB should be filled.
i am using C# as my code behind.
Can anyone help me to proceed..
Awaiting ur reply
You need the <asp:HyperLinkField />
<asp:GridView>
<Columns>
<asp:HyperLinkField HeaderText="Id" DataTextField="YourID" DataNavigateUrlFields="YourID"
DataNavigateUrlFormatString="SecondPage.aspx?Id={0}" />
</Columns>
</asp:GridView>
You might need to remove the AutoGenerateColumns="true" property and type the fields yourself, selecting only the columns you want to show - using <asp:BoundFied DataField="ColumnName" />
In case you want to pass multiple values in the querystring, separate the fields with comma
DataNavigateUrlFields="YourID, SecondField"
and your format string would be
DataNavigateUrlFormatString="SecondPage.aspx?Id={0}&param2={1}"
Other links
HyperLinkField.DataNavigateUrlFormatString Property
How to pass multiple values in HyperlinkField
You can use a TemplateField column in your GridView:
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="linkToDetails" runat="server" NavigateUrl='Details.aspx?empId=<%# Eval("empId") %>' Text='<%# Eval("empId") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
On the Details.aspx page you should get the empId from the QueryString and get the details from the database.

Making a GridView footer data bound like a Row data

I have an ASP.NET project created with C# that uses GridViews. The footer row contains a ratio of a total based on the column data over a set value from the data saying how many there should be. The user needs to be able to modify the second value and have the footer update. I am not able to find out how to do this or even if it is possible. I contemplated using another GridView underneath, but ensuring the column lines sync between the two is a nightmare. Any ideas?
Also, when I change the column data (using Edit/Update rows), the total is not updated when I click on Update, but does when I click on Edit again. Can anyone tell me why this is and how to update the total in the footer on Updating?
If you find that your edited fields are refreshed "one click behind" typically it's due to thinking you've rebound your GridView but actually haven't or you've rebound before making the Update.
With Gridview, a typical scenario whenever you place fields in a footer is to calculate it's values during databinding operations of the Page Lifecycle
It goes like this, your .aspx file defines some footer fields, typically some BoundField that has been converted to TemplateFields. Here's a snippet:
<asp:GridView ID="GridView1" runat="server" ShowFooter="true" ...>
<Columns>
<asp:BoundField DataField="Field1" HeaderText="Title" SortExpression="Field1" />
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Field2") %>' ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="FooterLabel1" runat="server" Text="" ></asp:Label>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
GridView Events in the code behind: This is generally what you need to do to populate footer fields based on changing Row Values. This is VB but you should be able to convert it easily enough.
// Create a variable at the Page level that will exist for
// the duration of the Page LifeCycle
Private FooterLabel1SubTotal as Double
// Initialize
Private Sub GridView1_DataBinding(sender As Object, e As EventArgs) Handles GridView1.DataBinding
FooterLabel1SubTotal = 0.0
End Sub
// Accumulate
Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataRow Then
Dim Field2 as Label = e.Row.FindControl("Field2")
FooterLabel1SubTotal += Convert.ToDouble(Field2.Text)
End If
End Sub
// Populate Footer with formated value
Private Sub GridView1_DataBound(sender As Object, e As EventArgs) Handles GridView1.DataBound
FooterLabel1 = GridView1.FooterRow.FindControl("FooterLabel1")
FooterLabel1.Text = String.Format("{0:F2}", FooterLabel1SubTotal)
End Sub
Now if you use any of the Built in Editing features of the GridView, that will cause a Postback and will cause the GridView to rebind, which should recalculate the footer fields each time.

Gridview textbox on Page_load enable edit

using Visual.Web.Developer.2010.Express;
using SQL.Server.Management.Studio.2008.R2;
N00b here,
I've got the gridview to look the way I want it to (a textbox inside of the ItemTemplate). The Textbox's class has some client-sideJS that enables a save button (an asp:LinkButton set to look like a Jquery UI save icon) to become visible after the Textbox's .keypress event fires..
Now for my question..I've looked everywhere, but I can't get how to have gridview put the Sql server db content in that textbox on Page_load (one textbox + <br /> for each row). I'm only printing one collumn from the Sql server db into the Gridview.. Also, how would I bind the asp:LinkButton save button to gridview's save event? If there is a more effecient way to do this? If you have some insight for me, please give me your opinion/!
My .aspx code
<asp:TemplateField >
<ItemTemplate>
<asp:TextBox ID="TextBox1" class="hexen" runat="server" DataField="TbValue" SortExpression="TbValue">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:FluxConnectionString %>"
SelectCommand="SELECT [TbValue] FROM [InvestigateValues]">
</asp:SqlDataSource>
Thanks in advance!
Change your text box to
<asp:TextBox ID="TextBox1" class="hexen" runat="server" text='<%#Bind("TbValue")%>' />
This will enable two way databinding.
Here is an article to get you started: http://www.devx.com/DevX/Article/35058.
The grid view and SqlDataSource expose Insert, Update and Delete event/methods. These are on a row level, not grid level.
The way I would approach your problem would be to have an onclick event for your link button that iterates through the gridview, get the data from each text box and then perform the appropriate data base action in the code behind.

Set DetailsView as selected row of GridView

I am creating a GridView/DetailsView page. I have a grid that displays a bunch of rows, when a row is selected it uses a DetailsView to allow for Insert/Update.
My question is what is the best way to link these? I do not want to reach out to the web service again, all the data i need is in the selected grid view row. I basically have 2 separate data sources that share the same "DataObjectTypeName", the first data source retrieves the data, and the other to do the CRUD.
What is the best way to transfer the Selected Grid View row to the Details View? Am I going to have to manualy handle the Insert/Update events and call the data source myself?
Is there no way to link these two so they use the same data source ?
<asp:GridView ID="gvDetails" runat="server" DataKeyNames="ID, Code"
DataSourceID="odsSearchData" >
<Columns>
<asp:BoundField DataField="RowA" HeaderText="A" SortExpression="RowA" />
<asp:BoundField DataField="RowB" HeaderText="B" SortExpression="RowB" />
<asp:BoundField DataField="RowC" HeaderText="C" SortExpression="RowC" />
....Code...
<asp:DetailsView ID="dvDetails" runat="server" DataKeyNames="ID, Code"
DataSourceID="odsCRUD" GridLines="None" DefaultMode="Edit" AutoGenerateRows="false"
Visible="false" Width="100%">
<Fields>
<asp:BoundField DataField="RowA" HeaderText="A" SortExpression="RowA" />
<asp:BoundField DataField="RowB" HeaderText="B" SortExpression="RowB" />
<asp:BoundField DataField="RowC" HeaderText="C" SortExpression="RowC" />
...
The standard way to do it would be to have the selected item of the griview be a control parameter to the objectdatasource you have wired up to the detailsview. I would probably not worry too much about the overhead of retreiving data that you already have unless you are catering to users with such slow connections that you want to avoid roundtrips to the webserver at all costs.
If you really want to avoid that thenyou could pull the data out of the gridview using javascript/jquery and then do your inserts/updates via ajax calls. It would require lots more coding though.
This is a really old thread, but in case anyone came here looking for an answer like I did, a simple solution is to add this function to your code:
(Note that this only works if the rows in your GridView match the entries in your DetailsView.)
protected void GridView1_OnSelectedIndexChanged(object sender, EventArgs e)
{
DetailsView1.SetPageIndex(GridView1.SelectedIndex);
}
And modify the GridView and DetailsView to include these settings:
<asp:GridView ... OnSelectedIndexChanged="GridView1_OnSelectedIndexChanged" ... >
<asp:DetailsView ... AllowPaging="True" ... >
This will make the selected page in the DetailsView match the selected index in the GridView.
You can hide the paging options in the DetailsView properties if you dont want users to navigate using paging in the DetailsView.

Categories

Resources