How do I send multiple users message using a gridview with templates - c#

How do I send mltiple users message using a griview which should be connected to two tables namely login(from where usernames will be retrieved and shown) and then the second table message (where a message is to be stored for particular usernames). I have connected it to login but I am not able to insert values into message table. Message table has msg_id , username and message columns.
Here is the design:
.aspx
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
EnableModelValidation="True" DataSourceID="SqlDataSource1"
onrowcommand="GridView2_RowCommand">
<Columns>
<asp:BoundField DataField="username" HeaderText="username"
SortExpression="username" />
<asp:BoundField DataField="password" HeaderText="password"
SortExpression="password" />
<asp:BoundField DataField="utype" HeaderText="utype" SortExpression="utype" />
<asp:BoundField DataField="ptype" HeaderText="ptype" SortExpression="ptype" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:AutomobileConnectionString14 %>"
SelectCommand="SELECT * FROM [login] WHERE ([utype] LIKE '%' + #utype + '%')">
<SelectParameters>
<asp:Parameter DefaultValue="U" Name="utype" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</asp:Content>
aspx.cs code
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("cc"))
{
TextBox txt1 = (TextBox)GridView2.FooterRow.FindControl("TextBox1");
foreach(GridView gr in GridView2.Rows)
{
CheckBox chk = (CheckBox)gr.FindControl("CheckBox1");
if (chk.Checked)
{
Object ob = GridView2.DataKeys[gr.RowIndex].Value;
}
now I am stuck her how can I insert values into other table message when it is already connected to Login table. Help me what I want to accomplish here is send message to checked users.

Try below :
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" DataKeyNames="userId"
OnRowCommand="GridView2_RowCommand" OnRowEditing="GridView2_RowEditing" OnRowUpdated="GridView2_RowUpdated" OnRowUpdating="GridView2_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="Username">
<ItemTemplate>
<asp:Label Text='<%# Eval("username") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="password" HeaderText="password"
SortExpression="password" />
<asp:BoundField DataField="utype" HeaderText="utype" SortExpression="utype" />
<asp:BoundField DataField="ptype" HeaderText="ptype" SortExpression="ptype" />
<asp:TemplateField>
<ItemTemplate>
<asp:Label Text='<%# Eval("messgae") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtMsg" runat="server"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
On RowDataBound event to set the edit textbox for message by find control.
And refer to code for inline editing on check box click.
http://www.c-sharpcorner.com/UploadFile/9f0ae2/gridview-edit-delete-and-update-in-Asp-Net/
http://www.codeproject.com/Articles/23471/Editable-GridView-in-ASP-NET

Related

Get Gridview Datakey from nested gridview

I've got a gridview nested inside another gridview. What I need is that on the inner gridview get the DataKey from the outer gridview.
How can I pass it?
Thanks.
UPDATE
<asp:GridView ID="gvPeople" runat="server" AutoGenerateColumns="false" CssClass="Grid" DataKeyNames="person_id" OnRowDataBound="gvPeople_RowDataBound">
<Columns>
<asp:TemplateField HeaderStyle-Width="10px" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<img alt = "" style="cursor: pointer" src="images/glyphicons/png/glyphicons_236_zoom_in.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display: none">
<asp:GridView ID="gvDocuments" runat="server" AutoGenerateColumns="false" CssClass = "ChildGrid" DataKeyNames="document_id" ShowFooter="true"
OnRowCommand="gvDocuments_RowCommand" OnRowDataBound="gvDocuments_RowDataBound" OnRowDeleted="gvDocuments_RowDeleted" OnRowDeleting="gvDocuments_RowDeleting"
GridLines="Horizontal" >
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="document_date" HeaderText="Document Date" />
<asp:BoundField ItemStyle-Width="100px" DataField="value" HeaderText="Value" DataFormatString="{0:#,##.00 €}" />
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button runat="server" ID="delbutton" CommandArgument='<%# Eval("document_id") %>' CommandName="Delete" Text="Delete" />
<asp:Button runat="server" ID="editbutton" CommandArgument='<%# Eval("document_id") %>' Text="Edit" UseSubmitBehavior="false" />
</ItemTemplate>
<FooterTemplate>
<asp:Button runat="server" ID="newdoc" CommandName="New" Text="New Document" UseSubmitBehavior="false" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="150px" DataField="name" HeaderText="Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="ndocs" HeaderText="Nº of Documents" />
<asp:BoundField ItemStyle-Width="150px" DataField="total_cost" HeaderText="Total Cost" DataFormatString="{0:#,#0.00 €}" />
</Columns>
</asp:GridView>
Here is my aspx code, which is all working, with the excpetion of the new document button, which runs a javascript button, as the edit button, but on this one I need to pass the person_id, from the row of the gvPeople, so when I create a new gvDocuments row, it will make it to that person id.
Thanks.
Just put it to work.
Add a hiddenfield before the child gridview with the value that I want.
On the RowDataBound of the child gridview, added this:
string str= ((HiddenField)e.Row.Parent.Parent.Parent.FindControl("hf")).Value.ToString();
And now use the str value for anything that I want.
You need to first access each of the parent gridview row then access the child gridview row then access the datakey.
Example:
foreach (GridViewRow rowPeople in gvPeople.Rows)
{
GridView gvDocuments = (GridView)rowPeople.FindControl("gvDocuments");
//this will get you the outer/parent gridview datakeys
gvDocuments.DataKeys[rowPeople.RowIndex].Values[0].ToString();
foreach (GridViewRow rowDocuments in gvDocuments.Rows)
{
//this will get you the inner/child gridview datakeys
gvDocuments.DataKeys[rowDocuments.RowIndex].Values[0].ToString();
}
}
Let me know if that works for you!

ASP.NET SqlDataSource filter behaviour

I have a GridView object fed trough a SqlDataSource. In the same form I have also a number of TextBoxes used to build a filtering expression for the datasource. The filtering is started by pressing a Button.
<asp:GridView
DataSourceID="sdsTable1"
OnSorting="gvTable1_Sorting"
OnPageIndexChanging="gvTable1_PageIndexChanging"
runat="server"
CssClass="list_table"
ID="_gvTable1"
CellPadding="0" CellSpacing="0"
AutoGenerateColumns="false"
EmptyDataText="No data."
ShowHeader="true" ShowFooter="true"
AllowSorting="true"
AllowPaging="true"
PageSize="10"
OnRowDataBound="gvTable1_RowDataBound" >
<HeaderStyle CssClass="header" />
<FooterStyle CssClass="footer" />
<PagerSettings
Visible="true"
Mode="NumericFirstLast"
PageButtonCount="3"
Position="Bottom"
NextPageText="Next page"
PreviousPageText="Prev page"
FirstPageText="First page"
LastPageText="Last page" />
<RowStyle CssClass="odd" />
<AlternatingRowStyle CssClass="even" />
<PagerStyle HorizontalAlign="Center" />
<Columns>
<asp:TemplateField Visible="false">
<HeaderTemplate> </HeaderTemplate>
<ItemTemplate>
<%#Eval("id")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date" SortExpression="date">
<ItemTemplate>
<%#Eval("date","{0:dd/MM/yyyy HH:mm:ss}")%>
</ItemTemplate>
<FooterTemplate>
TOTALE:
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price" SortExpression="price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Bind("price","{0:F2} €") %>'>></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" Text="0"></asp:Label
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField DataField="description" HeaderText="Description" SortExpression="description" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sdsTable1" runat="server"
ConnectionString="<%$ ConnectionStrings:_db %>"
ProviderName="<%$ ConnectionStrings:_db.ProviderName %>"
DataSourceMode="DataSet"
SelectCommand=" SELECT id, id_user, price, description FROM view1 WHERE id_user = #id_user;">
<SelectParameters>
<asp:SessionParameter Type="Int32" Name="id_user" SessionField="USER_ID" />
</SelectParameters>
</asp:SqlDataSource>
In codebehind (in the event hanlder associated with the Button mentioned above) I build up the filter expression chaining TextBoxes values, with this code:
if (!string.IsNullOrWhiteSpace(_txtFilter0.Text.Trim()))
{
_sFilter += "(description LIKE '%" + _txtFilter0.Text.Trim() + "%')";
}
if (!string.IsNullOrWhiteSpace(_txtFilter1.Text.Trim()))
{
if (!string.IsNullOrWhiteSpace(_sFilter))
_sFilter += " AND";
_sFilter += "(description LIKE '%" + _txtFilter1.Text.Trim() + "%')";
}
sdsTable1.FilterExpression = _sFilter;
Everything works until I clear the fields that leads to an empty filter, im such circumstances I expected to retrieve all the records but for some reason, in this case, the last recordset is kept and shown apparently without a reason.
I tried also to disable the SQLDataSource caching feature without luck:
EnableCaching="false"
I tried also to issue a Select command, again without luck:
sdsTable1.Select(DataSourceSelectArguments.Empty);
Where I'm wrong?
Your _sFilter property will be persisted across postbacks, so as you're only updating it when your filter text boxes are not empty it will remain at the last set value when you clear them. Putting a breakpoint in your code at the line _sdsTable1.FilterExpression = _sFilter; should confirm this.
To solve the issue, either clear the _sFilter property before rebuilding it in your event handler, or write an additional check:
if (string.IsNullOrWhiteSpace(_txtFilter1.Text.Trim()) & string.IsNullOrWhiteSpace(_txtFilter0.Text.Trim()) )
{
_sFilter = null;
}

Paging not working in GridView when ajax control is removed

I have a grid view in my aspx page. I have enabled paging also.
Paging is working fine when an ajax control is in page, but when I removed the ajax control paging is not working anymore. ie, on clicking page number 2 grid becomes empty.
What could be the possible reason? Please suggest a solution.
code
<asp:GridView ID="SitesGrid" runat="server" AllowPaging="True" AllowSorting="True" DataSourceID="SitesDataMgr" AutoGenerateColumns="False" DataKeyNames="ID" CellPadding="3" CellSpacing="3" OnRowDataBound="viewSite_RowDataBound" class="tbl_blck gridtable clearfix" PageSize="4" EmptyDataText="No rows found">
<Columns>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="clientID" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" HeaderStyle-ForeColor="White" SortExpression="ClientName">
<ItemTemplate>
<asp:Label ID="clientLabel" runat="server" Text='<%# Bind("ClientName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status" HeaderStyle-ForeColor="White" SortExpression="SiteStatus">
<ItemTemplate>
<asp:Label ID="siteLabel" runat="server" Text='<%# Bind("SiteStatus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Details" HeaderStyle-ForeColor="White" >
<ItemTemplate>
<asp:LinkButton ID="viewSite" runat="server" OnClick="viewSite_click" CausesValidation="False" CommandName="Edit"
Text="View"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:ObjectDataSource ID="SitesDataMgr" runat="server" ConvertNullToDBNull="True" OldValuesParameterFormatString="{0}" SelectMethod="GetAllSitesByUser" FilterExpression="ClientName LIKE '%{0}%'" TypeName="Creation.DataMgr">
<SelectParameters>
<asp:SessionParameter Name="createdUserID" Type="String" SessionField="strUserName" />
</SelectParameters>
<FilterParameters>
<asp:ControlParameter Name="ClientName" ControlID="txtSearch" PropertyName="Text" />
</FilterParameters>
</asp:ObjectDataSource>
It looks like you have not added the SelectCount method to your ObjectDataSource.
This is required for the ObjectDatasource to correctly page your data.
Your select method needs the int parameters maximumRows and startRowIndex This is the default parameter names required for paging. if you do have them in. Please use them to filter your data.

asp.net entity framework <%# Bind("linkedTable.Field") %>

.NET 4 ASP.NET
I have a DetailsView that is displaying an entity framework record for a table that has a linked lookup table. I have an asp:BoundField with the datafield set as "linkedTable.Field" and it displays a value.
<asp:BoundField DataField="linkedTable.Field" HeaderText="linkedTable.Field"
SortExpression="linkedTable.Field" />
I am trying to use that value in an asp:TemplateField but when I try to get it using:
<asp:TemplateField HeaderText="Field" SortExpression="linkedTable.Field" >
<EditItemTemplate>
<asp:Label runat="server" ID="lblField" Text='<%# Bind("linkedTable.Field") %>' />
</EditItemTemplate>
</asp:TemplateField>
Nothing shows up in the label. I can change the Bind() to a field that is not part of the linked table and it works (i.e. the "ID" field). My problem is I don't understand why the linkedtable.Field value shows up in one context and not in the other.
FYI, my data connection is a EntityDataSource
<asp:EntityDataSource ID="edsNYSEDaily" runat="server"
ConnectionString="name=ServerDBEntities"
DefaultContainerName="ServerDBEntities" EntitySetName="tblNYSE"
EntityTypeFilter="tblNYSE" EnableUpdate="True" EnableFlattening="true"
AutoGenerateWhereClause="True" Select="" Where="">
<WhereParameters>
<asp:QueryStringParameter DefaultValue="0" Name="ID"
QueryStringField="ID" Type="Int32" />
</WhereParameters>
Let me know if you need any other information. I am stuck
Ok, discovered the problem:
Needed to add Include="linkedTable" to the EntityDataSource tag. Still not sure why it was even working in the <asp:DataBound /> tag.
Source for the answer: forums.asp.net
Copy of the text:
you should start here: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.entitydatasource.include.aspx
notice that, you won't be able to Bind (I mean two-way data-binding) the related entities (see the remarks there).
and, you'd have to use a TemplateField for those properties.
see this example (I used the link table 'TableAB' for EntitySetName and included the other two):
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="EntityDataSource1">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="IDA" HeaderText="IDA" SortExpression="IDA" />
<asp:BoundField DataField="IDB" HeaderText="IDB" SortExpression="IDB" />
<asp:TemplateField HeaderText="TableA Name">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("TableA.NameA") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TableB Name">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("TableB.NameB") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=ABLinkEntities"
DefaultContainerName="ABLinkEntities" EnableDelete="True" EnableFlattening="False"
EnableInsert="True" EnableUpdate="True" EntitySetName="TableABs" Include="TableA,TableB">
</asp:EntityDataSource>
you'll have to re-consider the updates and deletes, you could do them manually.

Gridview why all visible rows are set to dirty?

I'm using the BulkEditGridView control as discussed http://roohit.com/site/showArc.php?shid=bbb62, and it's perfect for my needs. The problem I'm having is that whenever I save, every visible row (I have paging enabled) gets updated. Stepping through the code I see that grid.DirtyRows.Count is equal to the number of items per page minus 1 when I click the save button.
I can't find where rows are set as dirty. Any suggestions where I can look?
My code-behind has only this:
using System;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Collections;
using System.Data.Common;
public partial class MSDS_MSDS_Admin_GridUpdate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gridMSDS.DataKeyNames = new String[] { "id" };
gridMSDS.DataBind();
}
}
}
EDIT: Here is the aspx code.
<%# Page Language="C#" MasterPageFile="~/MSDS/MSDS.master" AutoEventWireup="true" EnableEventValidation="false" CodeFile="GridUpdate.aspx.cs" Inherits="MSDS_MSDS_Admin_GridUpdate" Title="Untitled Page" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<%# Register Assembly="RealWorld.Grids" Namespace="RealWorld.Grids" TagPrefix="cc2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="PageContent" runat="Server">
<br />
<asp:Button ID="btnSave" runat="server" Text="Save" Width="100%" />
<cc2:BulkEditGridView ID="gridMSDS" runat="server" AllowPaging="True" AllowSorting="True"
DataSourceID="sqlData" EnableInsert="False" InsertRowCount="1" PageSize="20"
SaveButtonID="btnSave" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" Visible="false"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="ChemicalTitle" HeaderText="ChemicalTitle" SortExpression="ChemicalTitle" />
<asp:TemplateField HeaderText="SheetDate" SortExpression="SheetDate">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("SheetDate") %>' Width="85px"></asp:TextBox>
<cc1:CalendarExtender ID="TextBox1_CalendarExtender" runat="server" Enabled="True"
TargetControlID="TextBox1">
</cc1:CalendarExtender>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("SheetDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Filename" HeaderText="Filename" SortExpression="Filename" />
<asp:BoundField DataField="Manufacturer" HeaderText="Manufacturer" SortExpression="Manufacturer" />
<asp:BoundField DataField="UsageDept" HeaderText="UsageDept" SortExpression="UsageDept" />
<asp:TemplateField HeaderText="Notes" SortExpression="Notes">
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("Notes") %>' TextMode="MultiLine"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%# Bind("Notes") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status" SortExpression="Status">
<EditItemTemplate>
<asp:DropDownList ID="ddlStatus" runat="server" DataSourceID="sqlStatus" DataTextField="DisplayValue"
DataValueField="Value" SelectedValue='<%# Bind("Status") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="sqlStatus" runat="server" ConnectionString="<%$ ConnectionStrings:NCLWebConnectionString %>"
SelectCommand="getOptionList" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="msds_Status" Name="ListName" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlStatus" runat="server" DataSourceID="sqlStatus" disabled="true"
BackColor="White" DataTextField="DisplayValue" DataValueField="Value" SelectedValue='<%# Bind("Status") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="sqlStatus" runat="server" ConnectionString="<%$ ConnectionStrings:NCLWebConnectionString %>"
SelectCommand="getOptionList" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="msds_Status" Name="ListName" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Health" SortExpression="Health">
<EditItemTemplate>
<center>
<asp:TextBox ID="TextBox2" runat="server" Style="text-align: center" Text='<%# Bind("Health") %>'
Width="25px"></asp:TextBox>
</center>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Health") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Fire" SortExpression="Fire">
<EditItemTemplate>
<center>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Fire") %>' Width="25px"></asp:TextBox></center>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("Fire") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reactivity" SortExpression="Reactivity">
<EditItemTemplate>
<center>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("Reactivity") %>' Width="25px"></asp:TextBox></center>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("Reactivity") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DateUpdated" HeaderText="DateUpdated" SortExpression="DateUpdated"
ReadOnly="True" />
<asp:BoundField DataField="UpdatedBy" ReadOnly="True" HeaderText="UpdatedBy" SortExpression="UpdatedBy" />
</Columns>
</cc2:BulkEditGridView>
<asp:SqlDataSource ID="sqlData" runat="server" ConnectionString="<%$ ConnectionStrings:NCLWebConnectionString %>"
SelectCommand="SELECT [ID], [ChemicalTitle], dbo.dateOnly([SheetDate]) As [SheetDate], [Filename], [Manufacturer], [UsageDept], [Notes], isnull([Status], 4) as [Status], [Health], [Fire], [Reactivity], [DateUpdated], [UpdatedBy] FROM [msds_Sheets] ORDER BY [ChemicalTitle]"
UpdateCommand="msds_UpdateSheet" UpdateCommandType="StoredProcedure">
<UpdateParameters>
<asp:Parameter Name="ID" Type="Int32" />
<asp:Parameter Name="ChemicalTitle" Type="String" />
<asp:Parameter Name="SheetDate" DbType="DateTime" />
<asp:Parameter Name="Filename" Type="String" />
<asp:Parameter Name="Manufacturer" Type="String" />
<asp:Parameter Name="UsageDept" Type="String" />
<asp:Parameter Name="Notes" Type="String" />
<asp:Parameter Name="Status" Type="Int16" />
<asp:Parameter Name="Health" Type="Int16" />
<asp:Parameter Name="Fire" Type="Int16" />
<asp:Parameter Name="Reactivity" Type="Int16" />
<asp:ProfileParameter Name="UpdatedBy" Type="String" PropertyName="Username" />
</UpdateParameters>
</asp:SqlDataSource>
</asp:Content>
Testing Procedure is as follows:
-Load the page.
-Edit something in the first row.
-Click save button.
The code you have posted looks fine. My test code is almost identical to yours, but I cannot produce the unwanted results you are seeing.
The most significant difference between your code and mine is that I don't have the code for your master page. My master page is the default page created by VS 2008. Other than that, the differences are in the SQL and the underlying database. Specifically, I am not using any stored procedures, and I have made reasonable assumptions about the data types involved: the ID is int, Status is smallint, SheetDate is Date, DateUpdated is DateTime, and everything else is varchar.
EDIT: Your SheetDate appears to be just the date portion of an underlying DateTime value from the database. The fact that your query transforms the underlying data value for display purposes is not relevant, because the grid view can't tell that it is getting a modified value. END OF EDIT
Here are a few suggestions for diagnosing the problem:
Test without master page, or with a
very simple dummy master page that is
guaranteed not to have scripts that
interact with the BulkEditGridView.
Since the ToolkitScriptManager is
apparently on your master page, you will
need to either move the script
manager control to the page itself,
or else temporarily get rid of the
CalendarExtender element, which
requires the script manager.
Temporarily replace the Status
template field with a bound data
field, to eliminate possibility of
interaction with the DropDownList.
The drop down list did not cause
problems in my tests, but there may
be subtle differences between your
code and mine.
If neither of these help, then a possible cause is a problem in your
version of the BulkEditGridView.
EDIT - Additional suggestions for diagnosis:
Based on examination of the source code for BulkEditGridView, it appears that the code is properly tracking which rows of the grid are "dirty". Therefore, the most likely cause of a spurious dirty row is that one or more controls in the grid are incorrectly detecting a change to their data content. You can detect this in the debugger, using the source code for BulkEditGridView, rather than the pre-compiled DLL.
Set a breakpoint at the start of HandleRowChanged, the event handler which detects changes in any cell of the grid. By examining the sender parameter of that object in the debugger, you can tell which controls in the grid are undergoing value changes. In particular, you will be able to tell which controls, if any, are incorrectly triggering a value change event.
Once you determine which control(s) are incorrectly reporting that their value has changed, you can focus on why this is happening.
END OF EDIT
Some other suggestions to improve the code are as follows. These will not solve the original problem, but will make the code cleaner:
In all of the template fields, remove the ItemTemplates. They can never be used, since the BulkEditGridView forces every row to be in the edit state.
In the code behind, the BindData()
call is not needed, since the source
data is specified in the declarative
markup, and therefore the grid view
control will automatically bind the
data.
I am not an expert in BulkEditGridView control, but this is what I found at Matt Dotson's blog entry
You may not be able to know that the row has been updated, unless you watch for the change explicitly. First, for each row add a change handler
protected override void InitializeRow(GridViewRow row, DataControlField[] fields)
{
base.InitializeRow(row, fields);
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.Controls.Count > 0)
{
AddChangedHandlers(cell.Controls);
}
}
}
You can use this snippet
private void AddChangedHandlers(ControlCollection controls)
{
foreach (Control ctrl in controls)
{
if (ctrl is TextBox)
{
((TextBox)ctrl).TextChanged += new EventHandler(this.HandleRowChanged);
}
else if (ctrl is CheckBox)
{
((CheckBox)ctrl).CheckedChanged += new EventHandler(this.HandleRowChanged);
}
else if (ctrl is DropDownList)
{
((DropDownList)ctrl).SelectedIndexChanged += new EventHandler(this.HandleRowChanged);
}
}
}
Then you define a dirty row list and add rows that needs to be updated there (in the event handler)
private List<int> dirtyRows = new List<int>();
void HandleRowChanged(object sender, EventArgs args)
{
GridViewRow row = ((Control) sender).NamingContainer as GridViewRow;
if (null != row && !dirtyRows.Contains(row.RowIndex))
{
dirtyRows.Add(row.RowIndex);
}
}
Finally, to commit changes, iterate through all the dirty rows and save changes
public void Save()
{
foreach (int row in dirtyRows)
{
this.UpdateRow(row, false);
}
dirtyRows.Clear();
}
And here is your ASPX code
<asp:Button runat="server" ID="SaveButton" Text="Save Data" />
<blog:BulkEditGridView runat="server" id="EditableGrid" DataSourceID="AdventureWorks" AutoGenerateColumns="False" DataKeyNames="LocationID" SaveButtonID="SaveButton" >
<Columns>
<asp:BoundField DataField="LocationID" HeaderText="LocationID" InsertVisible="False" ReadOnly="True" SortExpression="LocationID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Availability" HeaderText="Availability" SortExpression="Availability" />
<asp:BoundField DataField="CostRate" HeaderText="CostRate" SortExpression="CostRate" />
</Columns>
</blog:BulkEditGridView>

Categories