How can you read a gridview cell when editing besides textboxes? - c#

I having a little dilemma and Im not sure how to work around this issue. If I am editing a gridview, I am reading the rows as such
cmd.Parameters.Add("#X", SqlDbType.Char).Value = ((TextBox)GridView1.Rows[e.RowIndex].Cells[15].Controls[0]).Text;
cmd.Parameters.Add("#Y", SqlDbType.Char).Value = ((TextBox)GridView1.Rows[e.RowIndex].Cells[15].Controls[0]).Text;
When the gridview is in edit mode, both cells X and Y have textboxes because that is the default edit mode. I created the columns manually and I would like for cell X to be "read only". How can I change the code so that I can read the cell X without a textbox? Help would be greatly appreciated. Thanks!

This might be a bit too simple, but how about:
var lblHolder = (Label) GridView1.FindControl("lblMyLabel")
cmd.Parameters.Add("#X", SqlDbType.Char).Value = lblHolder.Text
Just search for your label (or whatever is holding your value) directly
Then your Grid View can look something like this
<asp:GridView ID="gvData" runat="server" AutoGenerateColumns="false" Width="95%" Font-Names="Verdana">
<RowStyle Height="40px" />
<Columns>
<asp:TemplateField HeaderText="Col1">
<ItemTemplate>
<asp:Label ID="lblMyLabel" runat="server"
Text='<%# eval("MyDataBaseField")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then you just need to connect a data source to the grid. There are of course loads of other ways to do it, but searching for controls by their Ids is a lot easier than trying to figure out their number in an array

Related

How to add a TextBox in a specific cell in GridView in ASP web forms?

This question may look repeating but I'm having a slightly different challenge. I have a GridView with multiple columns. The first column is a Button column and the rest are populated from the database.
Problem Statement:
When a user clicks the Edit button on a specific row, a TextBox should appear in the column called UnitRate in the GridView gv2. The default text of the TextBox should be the value / text of that same cell. This TextBox should appear only for that specific cell not for the entire column. The current GridView is shown below.
And I want something like this
Code for GridView
<asp:GridView ID="gv2" runat="server" Font-Size="Small" OnRowCommand="gv2_RowCommand">
<HeaderStyle BackColor="Yellow" />
<AlternatingRowStyle BackColor="LightGray" />
<RowStyle BackColor="LightGray" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn_edit" runat="server" Text="Edit" CssClass="btn btn-warning btn-sm" CommandName="editData" CommandArgument='<%# Container.DisplayIndex %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns></asp:GridView>
You can try something like this: https://www.c-sharpcorner.com/UploadFile/1e050f/edit-and-update-record-in-gridview-in-Asp-Net/
You can use the EditItemTemplate to make that UnitRate field a text box when the user clicks edit. You can then make the EditItemTemplate for all the rest of the fields to just be a label. The drawback is that you have to spell out all the columns explicitly rather than having them autogenerated, but that's unavoidable if you want something non-standard like this to happen, where one field is editable while others aren't.

Control 'DataLoading1_gdvDataGroups_ctl01_ctl00' of type 'DataControlLinkButton' must be placed inside a form tag with runat=server

I'm trying to export the contents of an ASP.NET gridView control to an Excel spreadsheet. To do this I've been using the code on this page.
When it gets to the RederControl(hw) line though my code blows up. I get an error like:
GridView must be placed inside a form tag with runat=“server” even after the GridView is within a form tag
To solve this I found this answer. However the main answer does not work and I think it is because my code is in an .ascx user control. With that in mind I tried the solutions in the second highest rated answer.
This time I get error relating to the DataControlLinkButtons similar to the title of this question.
My gridview contains hyperlinks inside in the cells of one column. I tried to remove them from their parent control prior to rendering with the following code (as per the second answer on that page)
List<int> gridIndexes=new List<int>();
for (int i = 1; i < gdvDataGroups.Controls[0].Controls.Count-1; i++)
{
gridIndexes.Add(gdvDataGroups.Controls.IndexOf(gdvDataGroups.Controls[0].Controls[i].Controls[8].Controls[1]));
gdvDataGroups.Controls.Remove(gdvDataGroups.Controls[0].Controls[i].Controls[8].Controls[1]);
}
but it didn't work for me and I got the same error.
Any ideas of how to approach this?
The gridView is as follows (with only the relevant 9th column included):
<asp:GridView ID="gdvDataFiles" SkinID="MediumSpace" runat="server" AutoGenerateColumns="False"
ShowHeader="true" Width="100%" OnPageIndexChanging="gdvDataFiles_PageIndexChanging"
AllowPaging="True" PageSize="20">
<Columns>
<asp:TemplateField HeaderText="Details" ItemStyle-Width="80px" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" Text='<%# Eval("RequestPKID") == null ? "Not available" : "View" %>'
NavigateUrl='<%# Eval("RequestPKID") == null ? "" : Eval("RequestPkid", "../Pages/BOLoadDetails.aspx?fileid={0}") %>'
Style="padding-top: 4px; display: block" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
No data file loads found
</EmptyDataTemplate>
</asp:GridView>
Ok turns out that I needed to disable the sorting on the grid prior to rendering the spreadsheet. I think it was the sort control buttons that were causing the problem.

DataBind and DataSource on a Gridview

I have done gridviews before, where I bind all SQL data from data safe reader or specify column names and binds at the javascript level. This is a bit different and I am a bit stumped on how to proceed.
I have a business class that handles all SQL data queries.
This class is called to Fetch a LIST. This list contains collections and child collections.
var _InfoList = BusinessObjectClass.Get(_CriteriaKey);
I can access the list as such:-
Txtbox1.Text = _InfoList.ID#.ToString();
Now I am trying to bind one of the collections in the LIST to a gridview.:-
C#:-
gvwMembers.DataSource = _InfoList.Members;
gvwMembers.DataBind();
Where Members is a collection...
But this syntax doesn't add any thing to the gridview...The gridview is empty.
Second methodology:-
I also tried doing something like this:-
List<BusinessObjectClass> Members = new List<BusinessObjectClass>();
Members = _InfoList.Members;
gvwVendors.DataSource = Members;
gvwVendors.DataBind();
But to no avail.. this is because the problem lies in the 2nd statement:-
Members = _InfoList.Members.... this is not a valid assignment...can anyone help with this?
After fleshing out some details in the comments, it is perfectly fine to have a simple GridView with no columns defined, but make sure AutoGenerateColumns is not false. The default is true. This will create a column for you, based on each property of the object being bound.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
</asp:GridView>
And in order to pick and choose which properties to display, define them in the <Columns> section.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Property1" HeaderText="Property1" />
<asp:TemplateField HeaderText="Property2">
<ItemTemplate>
<asp:Label ID="lblProperty2" runat="server" Text='<%# Eval("Property2") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Change displayed data in table created from SQL query in ASP.NET

I can't figure out how to search for this and get exactly what I need. I'm trying to figure out how to change the way a piece of data displays. So, for example, if I retrieve a tinyint that is either a 1 or 0, and I want to display either "yes" or "no" respectively, how do I go about that? Here is what I have in the aspx:
<ASP:DataGrid id="AdminDataGrid" runat="server"
AutoGenerateColumns="False" AllowSorting="true"
Width="700px" CellPadding="3" EnableViewState="True"
BackColor="#EEEEEE" BorderColor="Black" HeaderStyle-BackColor="Gray"
Font-Name="Verdana" Font-Size="8pt" Font-Names="Verdana"
>
<Columns>
<asp:BoundColumn DataField="Active" HeaderText="Active State" ReadOnly="true" SortExpression="Active" />
</Columns>
</ASP:DataGrid>
To be clear, I just want it to automatically update the value every time it pulls data from the SQL table.
I've been trying a few things, but I'm not sure when and how to make the change. Member objects:
DataTable DataTableAdmin = new DataTable();
DataView DataViewAdmin;
Then in page load:
DataTableAdmin = myDataAccessObject.GetTable(strQuery);
DataViewAdmin = new DataView(DataTableAdmin);
I tried something like:
if (DataTableAdmin.Columns[0] = "0")
{
DataTableAdmin.Columns[0] = "No";
}
else
{
DataTableAdmin.Columns.[0] = "Yes";
}
But I know that's not right because it doesn't know what row to do that on. But I'd like it to be universally applied to all rows anyway. Then I thought I could do something with the DataView using a filter:
DataViewAdmin.RowFilter("Active = '0'");
But then I'm not sure how I would apply changes to what I get back. Something else I was considering would be to replace the column with a series of checkboxes that would be checked or unchecked depending on what the value is. Then that could be checked or unchecked, and the value could be updated in the database.
This is coming from the Question I posted in the comments. Pretty funny both columns are named Active in the 2 posts.
<asp:TemplateField HeaderText="Active" SortExpression="Active">
<ItemTemplate><%# (Boolean.Parse(Eval("Active").ToString())) ? "Yes" : "No" %></ItemTemplate>
</asp:TemplateField>
C Shaper's answer got me on the right track, but it needed a decent amount of tweaking. First problem was: code blocks are not supported in this context. Changing the object to a TemplateColumn fixed that. Then it was failing to parse the value, saying the String was not recognized as a valid Boolean. After doing further research, I got it working with the following:
<asp:TemplateColumn HeaderText="Active" SortExpression="Active">
<ItemTemplate><%# Convert.ToBoolean(Convert.ToInt32(Eval("Active").ToString())) ? "Yes" : "No" %></ItemTemplate>
</asp:TemplateColumn>

Adding column to a gridview

I currently have a gridview that is set up and working properly but I ran into a little bit of an issue. My grid's datasource is being set from a DB table and one of the columns in the table is the numeric ID of another table. Rather than displaying this numeric ID in the grid, I need to display a description column off of the other table. Can I add an additional column to my current gridview just for display purposes?
Yes you can accomplish this by using a template on your ID field rather than creating a new field. This link has some examples. This way you can custom format your existing column.
You can use a data-set and bind this dataset to the gridview.
Using the data-set, you can add rows, columns. The below example is a good one to add rows/columns to the grid-view. You can also follow the same example with a little bit of tweaks.
http://www.codeproject.com/KB/aspnet/dynamic_Columns_in_Grid.aspx
Set AutoGenerateColumns to false, and define the columns that you want to display:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" CellSpacing="0" AutoGenerateColumns="false" Width="100%">
<RowStyle BackColor="#ffffff" />
<AlternatingRowStyle BackColor="#f5f5dc" />
<HeaderStyle BackColor="Beige" ForeColor="#333333" Font-Bold="true" Height="25px" />
<Columns>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<ItemTemplate>
<%# Eval("Address") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The change should be made in 3 locations:
The datasource should have the desc column brought back with it. Do the join in the database and bring it all back at once so the front end will not need to make an insane amount of calls.
On display, you can set the id column to invisible. This can be done on the code behind or on the aspx.
On edit, if it is a value that is based off of a look-up table, you will need to create a drop down list. You can query for more info if edit is needed, if not, the top two points should cover your needs.

Categories

Resources