In the code behind, I have the event handler set up like this:
protected void MyGrid(object sender, GridViewSortEventArgs e)
{
var NewDataSource = from d in MyList
orderby e.SortExpression
select d;
}
Now the problem is that MyList is null when the event handler takes over! I'm tracing it and I see it loaded fine, I see the gridview on the page with the correct data but as soon as I click a column header to sort the grid, the MyList goes to null! Why?
I've read multiple sources that say Gridview's do not persist the Gridview.DataSource property on postback. My understanding is that in term's of ASP.NET, a postback is any page load that is not the first pageload (see MSDN). I've got a situation with 2 very similar gridviews.
GvOne.DataSource is null on postback. GvTwo.DataSource is NOT null on postback.
The only big difference outside of a few differing columns is GvOne is populated with the Entity Framework and LINQ. GvTwo is populated by a DataTable filled by a SqlDataAdapter. Further, GvOne and GvTwo have a TemplateField with a TextBox that I use to gather user input. Both use the same code to pull the TextBox.Text on postback:
Changing GvTwo to use Entity Framework and LINQ is a potential solution, albeit a major undertaking. Does anyone know what is going on here? UPDATE (See my comment on Joel Etherton's Answer) Due to popular demand here is the code to populate the gridview within Page_Load event for GvTwo (GvOne is similar):
Searching through the code behind I found no other references to ordersGv.Datasource and no other events that are hooked into associated with the page life cycle.
In asp I want to add row to my gridview when I read barcode. But when I want to add second row , gridview.datasource = null. So, my first row is removed from gridview in TxtBxBarcode_TextChanged event.
TxtBxBarcode and gridview are in the different update panels.
How can I prevent this "gridview.datasource is null when Postback" ?
I have 4 gridviews on a page that get databound with a datatable from sql. So I have created the sort/paging events for each. These were working fine. However now they do not work.
I am not able to figure out why I am getting the null error at SqlDataSource10.Insert(); I tried running through break points and i checked the Insert statement and it has all the required values .. but I get error saying it cannot insert null into NrNarrativeDays. I am working off a sample at this link..
I wanted to get the total row count in a GridView's databound event handler, so I tried the following:
protected void grid_DataBound(object sender, EventArgs e) { GridView grid = (GridView)sender; DataSet data = grid.DataSource as DataSet; if (data == null) return; int totalRows = data.Tables[0].Rows.Count; }
The problem is that the grid.DataSource property is null. The DataSourceID property is not null, so does that mean that I can't access the DataSource object in the DataBound event handler unless I assign the DataSource property directly?
Edit1: Here is the code in my GridHelper class for adding rowcount to the BottomPagerRow. I would like to get rid of the requirement to pass in the ObjectDataSource, but can't because I need to use the Selected event to get total row count. Hence the reason for the question. I also think this might be better in a custom control where I can access ViewState, and/or create child controls during the Init event (I still have a problem to resolve with the way the pager renders with an extra cell), but then I'd still have the problem of how to get to the total row count when the DataSource itself doesn't appear to be available in any GridView events.
Edit 2: Not really relevant to the specific problem, but I resolved the problem I was having with the pager rendering so i've updated the code posted. I found the trick here: [URL]
#region Fields private int totalRows = -1; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="GridHelper"/> class. /// Adds EventHandlers to the GridView to display results from the ObjectDataSource in the footer. /// Marked as obsolete because AddResultsToFooter method provides a static access to the same functionality /// An instance of GridHelper is required by the passed in GridView to store the totalRows value between the two event handlers /// </summary> /// <param name="grid">The grid.</param> /// <param name="source">The ObjectDataSource linked to the GridView.</param> [Obsolete("Use AddResultsToFooter instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public GridHelper(GridView grid, ObjectDataSource source) { source.Selected += source_Selected; grid.PreRender += grid_PreRender; } #endregion #region Event Handlers private void grid_PreRender(object sender, EventArgs e) { GridView grid = (GridView)sender; if (grid.HeaderRow != null) grid.HeaderRow.TableSection = TableRowSection.TableHeader; //Add a cell to the bottom pager row to display the total results if (grid.BottomPagerRow == null || !grid.BottomPagerRow.Visible) return; //Get the control used to render the pager //http://michaelmerrell.com/2010/01/dynamically-modifying-the-asp-net-gridview-paging-control/ Table tblPager = grid.BottomPagerRow.Cells[0].Controls[0] as Table; if (tblPager == null) return; if (totalRows < 0) { //The DataSource has not been refreshed so get totalRows from round trip to client addResultsToPagerTable(tblPager, grid.Attributes["results"]); return; } int firstRow = grid.PageIndex * grid.PageSize + 1; int lastRow = firstRow + grid.Rows.Count - 1; string results; if (totalRows <= grid.PageSize) results = string.Format("<span class='grid-pager'>{0} Results</span>", totalRows); else results = string.Format("Results <b>{0}</b> to <b>{1}</b> of <b>{2}</b>", firstRow, lastRow, totalRows); addResultsToPagerTable(tblPager, results); //Need to store the information somewhere that is persisted via ViewState, and we don't have access to ViewState here grid.Attributes.Add("results", results); } /// <summary> /// Handles the Selected event of the source control. Gets the total rows, since it is not possible to access them from the GridView. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Web.UI.WebControls.ObjectDataSourceStatusEventArgs"/> instance containing the event data.</param> private void source_Selected(object sender, ObjectDataSourceStatusEventArgs e) { if (e.ReturnValue is DataView) totalRows = ((DataView)e.ReturnValue).Count; else if (e.ReturnValue is EntitySet) totalRows = ((EntitySet)e.ReturnValue).Count; } #endregion #region Private Methods private static void addResultsToPagerTable(Table tblPager, string results) { //http://michaelmerrell.com/2010/01/dynamically-modifying-the-asp-net-gridview-paging-control/ //Get a handle to the original pager row TableRow pagesTableRow = tblPager.Rows[0]; //Add enough cells to make the pager row bigger than the label we're adding while (pagesTableRow.Cells.Count < 10) pagesTableRow.Cells.Add(new TableCell { BorderStyle = BorderStyle.None }); //Add a new cell in a new row to the table TableRow newTableRow = new TableRow(); newTableRow.Cells.AddAt(0, new TableCell { Text = results, BorderStyle = BorderStyle.None, ColumnSpan = pagesTableRow.Cells.Count }); tblPager.Rows.AddAt(0, newTableRow); } #endregion #region Public Methods /// <summary> /// Adds EventHandlers to the GridView to display results from the ObjectDataSource in the footer. /// </summary> /// <param name="grid">The GridView.</param> /// <param name="source">The ObjectDataSource linked to the GridView.</param> public static void AddResultsToFooter(GridView grid, ObjectDataSource source) { if (grid == null) throw new ArgumentNullException("grid", "grid is null."); if (source == null) throw new ArgumentNullException("source", "source is null."); new GridHelper(grid, source); } #endregion
I am going to outline my setup then where i am failing
UpdatePanel1 - Contents : 3 textboxes and AddButton UpdatePanel2 - Contents : 1 GridView and SubmitButton
AddButton adds new row to DataTable with data from textboxes, binds DataTable to GridView SubmitButton sends data to database. The Adding of a row works to add the row to the gridview, but it won't add a second or third and so on, only adds the 1. SubmitButton belives the DataTable that GridView is databound to is null and won't send anything to the database. How can i get the datatable to persist between the two update panels? Do i use Sessions as my storage location? Page
I have setup my business object to have a create_date and edit_date members both datetime datatypes. My company want to display the create_date and edit_date fields in a gridview for each transaction. The problem i have is that after insterting a record it will have a valid create_date but no edit_date and when displayed in the gridview it defaults to datetime.minvalue (My default). How on earth do i show an empty field in my gridview for a null datetime field in the database?
I am using similar architecture to the Imar Spaanjaars example of a tiered solution. With a few small tweeks it has worked well for me for ages. I am passing a List<Database> to my object datasource which connects to my gridview.
If I write the following code, teh gridview will no longer show the data
gridview.DataSource = null; gridview.Databound.
My question is , I want to make the same thing with a user control that contain a gridview. when I use the user control in an aspx page, I am able to populate it with data, but when I try to make this code, the Datasource does not show, instead, I see .DV. So I tried this code but then , I do not see DataSource property instead I see DV (DataView), when I put .DV = null, I get an error message that the object is not in existed. any idea how to clear the user control gridview from its data.
here is my code for selectiong some records from db table
string strSql = "select * from mtblNBD where SentTo=@SentTo and InternalStatus Is NULL order by DeadLine desc"; SqlCommand com = new SqlCommand(strSql, con); com.Parameters.Add("@SentTo", SqlDbType.NVarChar, 50).Value = (string)Session["uname"];
here I am using parameters for SenTo field but not for NULL so it is ok... or should I use parameters for this field where value is NULL , if yes then how can I use parameter for this
I have page that has a datasource. The datasource executes a stored procedure and returns results. If the result is NULL, I'd like to forward the user to an error page. How would I accomplish this with ASP.NET and C#?
I've been trying solution I've found oline all day trying to get a GridView to Display its Header when its datasource returns 0 rows. So far, nothing has worked for me. I did come across an interesting bit of code, but I'm having a spot of bother with something else preventing me from getting it to work.
I need to retrive a value from a column of a table per stored proc. This is usually an integer, but also can be null. I get this value and store it in a session variable.
Later, I need to pass this same session variable to another stored proc.
Session["myVariable"] = ds.tables[0].rows[0][1]; // this can be null or an integer
somewhere else in the project, I need to pass it to another stored proc exactly as received.
here is my update query syntax.my problem is.if i update only logo1 and logo3 with null logo2 and img null then my query should be update the other record.just dont update null value record but other should be update.but below my query can not update any record.
UPDATE tbitem set itemname= @itemname,note=@note, price=@price,qty=@qty,logo1=@logo1, logo2=@logo2,logo3=@logo3,img=@img where id =@id and @logo1 is null and @logo2 is null and @logo3 is null and @img is null
I get a recordset returned from DB and try to load it. However sometimes field "LastRun" may be empty (NULL). when i have this it compiles fine but errors out when value is null m_LastRun = Convert.ToDateTime(r["LastRun"]); when I take out Convert.ToDateTime it doesn't even compile.
How can i get the values even when the Source or url is null from the below query
SELECT a.id, isnull((SELECT STUFF((SELECT '<li><a href="'+url+'">'+Source_Name+'</a> <span>(' + k.Source +')</span></li>' end FROM table1 i, table2 k, table3 j where i.CategoryID = j.Category_ID and i.CategoryID = c.Category_ID and i.Source = k.ID FOR XML PATH('')),1, 0, '')), '') AS Source_url, FROM @table4 c INNER JOIN table5 v on c.Category_ID = v.Category_ID
I have a datareader like so but when it encounters a NULL database value, I get the error message "Conversion from type 'DBNull' to type 'String' is not valid."
Dim myReader As SqlDataReader = myCommand.ExecuteReader() Dim yValues As New List(Of Double) With myReader If .HasRows Then While .Read yValues.Add(Double.Parse(.GetValue(0)))........
I have a dropdown list that uses an ObjectDataSource. The select method of the ObjectDataSource needs to localize the TextField, so i create a Dictionary<int, string> and use GetLocalResourceObject as such:
[Code]....
In the Local Resource file, there is status0, status1, and status2, all with a value (Deleted, Active, Inactive). The dropdown and object datasource like:
[Code]....
Now, if I use an ObjectDataSource and put the DropDownList's DataSourceID to it, I will get a null reference on the lookup to the GetLocalResourceObject. BUT If I manually set DataSource/DataBind on the dropdown list on Page_Load, it works fine:
[Code]...
OR If I move the status values to a global resource file and use GetGlobalResource instead of GetLocal, it works fine! Why can I not use an ObjectDataSource and LocalResourceObject in this way?
In following SQL query: SELECT DISTINCT CodeID, CodeDesc FROM Faults.TblFltClearCodes AS TblFltClearCodes
I am getting a list but there is no null value.Within this query I would like to get only one NULL value at the top and then the list.How to do this? Explicitly I am not allowed to give a null value in the table in DB.
iam using asp.net2.0 with c# with sql server 2000 when iam executing the procedure in local system it is working fine.but when iam executing in client system procedure returns null value, i have checked all connection string , and session value all are working