How to delete a row from a GridView using non-visible data? - c#

I'm writting a simple prototype front end using a GridView that is populated via function, rather than being linked directly to a SqlServer data source.
So I can delete a row/record from grid/underlying database I am currently
Setting the AutoGenerateDeleteButton = true
Displaying the unique record ids in the first column
Handling the RowDeleting event
Obtaining the id by getting the grid.Rows[e.RowIndex].Cells[idIndex].Text
Passing that number through to a function that does the deleting
This seems to be working just fine, but I would rather not display the ids to the users at they don't mean anything to them.
I tried setting the id column's Visible property to false, but this caused step 4 above to return an empty string - and so no record deleted.
So how do I store the hidded id number with each row?
Or am I going about this completely the wrong way?
Follow up to answers:
Thanks for both the answers, ended up going Eric's DataKeyNames way. For other people new to ASP.NET like I am, the steps I used where
Between the lines where I set the grids DataSource and called DataBind(), I added
grid.DataKeyNames = new string[] {"id"};
Then in the function handling the RowDeleting I got hold of my id using
grid.DataKeys[e.RowIndex].Value

GridView has a DataKeyNames property. When you bind a data source to the grid, you set the DataKeyNames (usually with just one name, your PK field). You don't show the PK, but you can get to it from code-behind.

Visible=false means don't render on the page. What you want is either to make it a template field and use a HiddenField to hold the value or set the style on the control to "display: none;". This would be the case if the client side code needed access to the value for an Ajax call or something.
Otherwise use the DataKeyNames property as #Eric Z Beard suggests.

Related

GridView - Hide Column but Use Value

I'm working with a GridView that I'm populating programmatically. In order to access the ID value, I have to have it as one of the columns (as opposed to a ListBox, where I was able to assign the value to each entry in a hidden way). Is there a way to hide that ID column, but still use the value?
The columns are being auto-generated through the code and I'm accessing the ID value using DataKeys.
Here's a general overview of what you can do. It's not complicated. You databind as usual, but while doing that you find the index of the ID column. Then you use that index to hide the column on the RowCreated event. If you search for how to hide a column using auto-generated columns, you'll run into several answers following the method I'm using for hiding.
Private IDColumnIndex As Integer //Class scope - we need to use it in multiple methods
Public Sub PageLoad() Handles Me.Load //or wherever your databind is happening
Dim source As New DataTable()
IDColumnIndex = source.Columns("id").Ordinal //Gets column index of "ID" column
view.DataSource = source
view.DataBind()
End Sub
//Hide our "ID" auto-generated column.
Public Sub view_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles view.RowCreated
e.Row.Cells(IDColumnIndex).Visible = False
End Sub
Assign the ID to the DataKeyNames collection will work fine, is that an issue for you? The data keys is available for each row, not showing up in the UI, but still accessible with the row data, so you can get the ID for each row. You just have to get it from the DataKeys collection, instead of the row directly.
You can add code to hide the first column (the ID) so that it doesn't appear, and rely on using the datakeynames to get the ID value... if that doesn't work, could you elaborate on why so I can adjust my answer..
You can get the ID value if you add the ID column to the DataKeyNames property of your GridView. msdn link here
myGrid.DataKeys[myRow.RowIndex].Value.ToString();
I usually add a visible column But then make the template for the colmn jus a space or something. Then in the ID for the column, I put the ID I want to track. This technique let's me easily find the ID of a row using javascript when the content has been rendered into HTML.
If you let the grid view do its business rendering with the hidden data keys, you may never find the ID in client side browser javascript in all that mess.

How to reorder columns in gridview dynamically

Similar questions may exists, but none of them seems to be helpfull. So I'll try to explain a more specific case, and see if anyone can help me :)
Here is the thing, I have a gridview with templatefields, and I want to let the user to specify the order those columns are shown. So, the user creates a view and decides which column to display first, second, and so on.
So basically, I need to change the order of the columns just after the grid is loaded with data.
Sounds easy huh? Well, apparently it's not. At least I couldn't achieve that just yet.
Some notes:
- Of course I have AutogenerateColumns set to false.
- Change the sql select columns order won't work because of previous item.
- And I'd like not to generate the columns by the code.
Any ideas?
You can modify the Gridview's Columns collection in your code-behind. So, one way of doing this is to remove the column from its current position in the collection and then re-insert it into the new position.
For example, if you wanted to move the second column to be the first column you could do:
var columnToMove = myGridView.Columns[1];
myGridView.Columns.RemoveAt(1);
myGridView.Columns.Insert(0, columnToMove);
If you need to move them all around randomly, then you might want to try to clone the field collection, clear the collection in the GridView, and then re-insert them all in the order you want them to be in.
var columns = myGridView.Columns.CloneFields();
myGridView.Columns.Clear();
myGridView.Columns.Add(columns[2]);
myGridView.Columns.Add(columns[0]);
etc..
I'm not 100% sure whether this all will work AFTER binding to data, so unless there's a reason not to, I'd do it in Page_Init or somewhere before binding.
I know this is an really old question but the suggested answer did not solve the problem fully.
The ViewState for the GridView will failed after remove / add a dynamic column.
If you need to bind any event, like OnRowCommand and OnRowUpdating, such events will not be fired.
Edit:
Look into this function if you need answers.
Protected Overrides Function CreateColumns(dataSource As PagedDataSource, useDataSource As Boolean) As ICollection

DataGridView C# Default Values in Rows During Edit Mode

I have a program that I use to enter values into a database using a gridview. The gridview is populated with an 'empty' result from a DataSet that queries that database from the table I want. This fills the grid with the proper columns that I want (ie. a grid with an empty row from a certain table in a db). When you fill in the columns, I take the data and manually update the db.
Basic example of how I use the gridview:
this.fullUutDataTableAdapter.Fill(this.dalsaUutDataSet.ResultsFullUut);
DataView dv = this.dalsaUutDataSet.ResultsFullUut.DefaultView;
Grid_modify.DataSource = dv;
foreach(DataGridViewRow dr in Grid_modify.Rows)
{
dr.Cells["YieldID"].Value = -1;
}
However, I want to have certain columns to have Default Values. I have tried changing the column's default value, but you cannot change the property, only 'GET' it. Alternatively, I tried parsing through the rows in the empty grid and filling in the values. This works fine when the grid loads up initially (values show up in proper places). HOWEVER, when as soon as I enter edit mode these values clear to nothing.
NEXT, I tried using some of the RowEdit Events and tried filling in values when edit mode is entered, however, this causes problems when you enter and leave edit mode. Seems to be a more complicated and messy way of doing things that seemingly necessary.
So the question really is, what is the best way to fill a gridview with default values in certain columns?
I would prefer the "cleanest" solution possible. However, I recognize that things don't always work out that way.....
Thanks for your help in advance! Cheers.
Take a look at this: How To Specify Default Values for DataGridView

Add user generated content to a database in asp.net

In page_load, I create a table and fill it with data gathered from a database. Then after allowing the user to modify it, I need to make the changes to the database. But I'm not sure how to do this. I have been looking around and now am more confused then when I started. My code to create the table looks like this:
delList.Controls.Clear();
Table tbl = new Table();
tbl.ID = "tbl1";
tbl.BorderWidth = 1;
delList.Controls.Add(tbl);
This code gets added to a placeholder:
<asp:PlaceHolder ID="delList" runat="server"></asp:PlaceHolder>
I want to have a button at the bottom of the page to allow the user to select in order to save the changes but I can't figure out how to do this. Mostly because there will be a lot of rows that need to be updated. I was thinking it might be easiest to parse through the table using javascript and then somehow calling a function to make update the database one row at a time. But I'm not sure if this is even possible.
All help will be greatly appreciated.
It would be a lot easier if you used a control that is specific to this kind of operation. I mean a control like GridView.
GridView displays the values of a data
source in a table where each column
represents a field and each row
represents a record. The GridView
control enables you to select, sort,
and edit these items.
The GridView control is used to
display the values of a data source in
a table. Each column represents a
field, while each row represents a
record. The GridView control supports
the following features:
Binding to data source controls, such as SqlDataSource.
Built-in sort capabilities.
Built-in update and delete capabilities.
Built-in paging capabilities.
Built-in row selection capabilities.
Programmatic access to the GridView object model to dynamically set properties, handle events, and so on.
Multiple key fields.
Multiple data fields for the hyperlink columns.
Customizable appearance through themes and styles.
i dont get how the User Can modify content in a Table, unless you have some form Controls like Textbox, Dropdown list?
You should be creating form fields dynamically, and adding it to a container/form on the Page along with a button (which could do a postback/ or handle JavaScript).
You Could iterate through all controls in a parent container or add custom attributes to your form elements, do that you can identify those fields in JS/Clientside.

How to hide the empty Column

Using C# & asp.net
if there is no data's in the table, gridview displaying one rows (it was empty)
I want to hide the gridview empty row.
How to do this.
Assuming that you can normally delete that one visible row just check that if a field that would normally have a value is empty and the row count is 1 then delete that row.
if(String.IsNullOrEmpty(mydatagrid.Rows[0][0].ToString()) && mydatagrid.Rows.Count==1) //Check a field that would normally have a value
{
mydatagrid.Rows.RemoveAt(0);
}
Let me know if this helps/works
If you are manually data binding than you can check at that time and hide or disable the control if there is no data. If you are data binding using the design view than you should subscribe to the DataBinding or the PreRender events on the control and check then.
you can check if the datatable doesn't have any rows
use:
mydatagrid.DataSource=null;
mydatagrid.DataBind();
As the other two comments you can either check in code and set MyDataGrid.Visible to true or false to hide the entire table, or you can not bind the datasource, or you can EmptyDataTemplate option to display whatever you want when there is no data for the GridView to display normally.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatemplate.aspx
The normal behavior for GridView is to render NOTHING if there are no data rows. (Well, almost nothing; it insists on rendering a <div> wrapper, but that'll be empty.)
If you specify an EmptyDataTemplate, however, a one-celled wrapper table is generated to contain whatever is in your template. Even if your template is empty, you'll get that wrapper table (with its one cell, empty). Sounds like the answer to your question is don't specify an EmptyDataTemplate.

Categories