I have a gridview with a data source. FOr some reason when I use the update button on the data source it is not updating. I am not getting a sql error and the query works fine when used directly.
<asp:GridView ID="viewStoryTime" runat="server" AllowPaging="True" AutoGenerateColumns="False"
DataSourceID="SqlDataSource10" DataKeyNames="NonScrumStoryId, PK_DailyTaskHours" BackColor="#DEBA84"
BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2"
Width="525px" OnRowEditing="viewStoryTime_OnRowEditing" OnRowCancelingEdit="viewStoryTime_OnRowCancelingEdit" OnRowUpdating="viewStoryTime_OnRowUpdating" OnRowUpdated="viewStoryTime_OnRowUpdated" >
<Columns>
<asp:BoundField DataField="Hours" HeaderText="Hours" SortExpression="Hours" />
<asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
<asp:BoundField DataField="ActivityDate" HeaderText="Date" SortExpression="ActivityDate" DataFormatString="{0:MM/dd/yyyy}" />
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource10" runat="server" ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT [DailyTaskHours].[PK_DailyTaskHours], [DailyTaskHours].[NonScrumStoryId], [DailyTaskHours].[Hours], [DailyTaskHours].[Notes], [DailyTaskHours].[ActivityDate] FROM [NonScrumStory], [DailyTaskHours] WHERE [DailyTaskHours].[NonScrumStoryId] = #nonScrumStoryId AND [NonScrumStory].[PK_NonScrumStory] = #nonScrumStoryId"
UpdateCommand="UPDATE [DailyTaskHours] SET [Hours] = #setEditHoursParam, [ActivityDate] = #setEditActivityDateParam, [Notes] = #setEditNotesParam WHERE [PK_DailyTaskHours] = #setDailyPKParam">
<SelectParameters>
<asp:QueryStringParameter Name="nonScrumStoryId" Type="String" />
</SelectParameters>
<UpdateParameters>
<asp:QueryStringParameter Name="setEditHoursParam" Type="String" />
<asp:QueryStringParameter Name="setEditActivityDateParam" Type="String" />
<asp:QueryStringParameter Name="setEditNotesParam" Type="String" />
<asp:QueryStringParameter Name="setDailyPKParam" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
Here is the c# that applies the parameters:
protected void viewStoryTime_OnRowEditing(object sender, GridViewEditEventArgs e)
{
SqlDataSource10.UpdateParameters["setDailyPKParam"].DefaultValue = viewStoryTime.DataKeys[e.NewEditIndex].Values["PK_DailyTaskHours"].ToString();
System.Diagnostics.Debug.WriteLine(viewStoryTime.DataKeys[e.NewEditIndex].Values["PK_DailyTaskHours"].ToString());
}
protected void viewStoryTime_OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlDataSource10.UpdateParameters["setEditHoursParam"].DefaultValue = e.NewValues[0].ToString();
SqlDataSource10.UpdateParameters["setEditActivityDateParam"].DefaultValue = e.NewValues[2].ToString();
SqlDataSource10.UpdateParameters["setEditNotesParam"].DefaultValue = e.NewValues[1].ToString();
System.Diagnostics.Debug.WriteLine(e.NewValues[0].ToString());
System.Diagnostics.Debug.WriteLine(e.NewValues[2].ToString());
System.Diagnostics.Debug.WriteLine(e.NewValues[1].ToString());
SqlDataSource10.Update();
SqlDataSource10.DataBind();
}
Nopte that the Debug.WriteLine() is so I can see the output of what should be going to the parameters, here is an example output:
Debug output:
4911
Debug output:
5.5
7/9/2013 12:00:00 AM
changed text
And when I press Update:
You don't need to call Update and DataBind methods in RowUpdating event handler because update is already happening and there you only need to fill values for parameters.
Another thing that needs attention but it is not relevant to your issue is the use of QueryStringParameter. If you don't use query string as a parameter source then it is better to use plain Parameter.
Related
I have an ASP.NET web form coded like this:
<asp:TextBox
ClientIDMode="Static"
ID="_txtExitDate"
runat="server"
EnableViewState="true" />
<asp:TextBox
ClientIDMode="Static"
ID="_txtEnterDate"
runat="server"
EnableViewState="true" />
<asp:Button
runat="server"
ClientIDMode="Static"
ID="_btnSearch"
Text="Search"
OnClick="_btnSearch_Click" />
<asp:GridView
ID="_gvRecords"
runat="server"
DataSourceID="_sdsRecords"
DataKeyNames="total_records"
CellPadding="0"
CellSpacing="0"
ShowHeader="true"
ShowFooter="true"
PageSize="20"
SelectedIndex="0"
Width="100%"
BorderStyle="None"
GridLines="Horizontal"
AutoGenerateColumns="false"
AllowSorting="true"
AllowPaging="true"
EmptyDataText="No records."
OnPageIndexChanging="_gvRecords_PageIndexChanging"
OnSorting="_gvRecords_Sorting" >
<SelectedRowStyle CssClass="SelRow" />
<HeaderStyle CssClass="GridHeader" />
<AlternatingRowStyle CssClass="AltRow" BackColor="#F7F5E9" />
<Columns>
<asp:BoundField DataField="region" HeaderText="Region" SortExpression="region" />
<asp:BoundField DataField="total_records" HeaderText="Records" SortExpression="total_records" />
</Columns>
</asp:GridView>
Of course these are only the relevant tags the layout is managed by other code that's not important.
The form include a SQLDataSource defined like this:
<asp:SqlDataSource
runat="server"
ConnectionString="<%$ ConnectionStrings:db %>"
ProviderName="<%$ ConnectionStrings:db.ProviderName %>"
ID="_sdsRecords"
OnSelecting="_sdsRecords_Selecting"
SelectCommand ="
SELECT
COUNT(DISTINCT(records.id)) AS total_records,
tab_cities.city_region AS region
FROM
records
INNER JOIN
tab_A ON records.id_subject = tab_A.id
INNER JOIN
tab_cities ON tab_cities.city_province_code = tab_A.province
WHERE
(records.mode = 'S')
AND (records.status = 'C')
AND (records.delete_date IS NULL)
AND (records.exit_date >= #exit)
AND (records.enter_date <= #enter)
GROUP BY
tab_cities.city_region
ORDER BY
total_records DESC">
<SelectParameters>
<asp:Parameter Direction="Input" DbType="DateTime" Name="exit" />
<asp:Parameter Direction="Input" DbType="DateTime" Name="enter" />
</SelectParameters>
</asp:SqlDataSource>
The codebehind is something like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
DateTime date = DateTime.Now;
var firstDayOfMonth = new DateTime(date.Year, date.Month-1, 1);
var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);
_txtExitDate.Text = firstDayOfMonth.ToShortDateString();
_txtEnterDate.Text = lastDayOfMonth.ToShortDateString();
}
}
protected void _btnSearch_Click(object sender, EventArgs e)
{
_sdsRecords.Select(DataSourceSelectArguments.Empty);
}
protected void _sdsNoleggi_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
DateTime _exit = DateTime.Parse(_txtExitDate.Text.Trim());
DateTime _enter = DateTime.Parse(_txtEnterDate.Text.Trim());
e.Command.Parameters["exit"].Value = _exit ;
e.Command.Parameters["enter"].Value = _enter ;
}
The form seems to work at startup i.e. the query returns the number of rows I'm expecting but if I try to change the value of _txtExitDate and _txtEnterDate and click on search button nothing changes.
_sdsNoleggi_Selecting() is triggered and command parameters are set correctly.
Another issue I cannot unserstand is why if I change <asp:Parameter /> with <asp:ControlParameter /> like this:
<SelectParameters>
<asp:ControlParameter DbType="DateTime" Name="exit" ControlID="_txtExitDate" PropertyName="Text" ConvertEmptyStringToNull="true" />
<asp:ControlParameter DbType="DateTime" Name="enter" ControlID="_txtEnterDate" PropertyName="Text" ConvertEmptyStringToNull="true" />
</SelectParameters>
parameters are not set correctly and then the whole query doesn't return any record (_sdsRecords_Selecting() event handler is removed in such case).
---- LATE UPDATE ----
As stated below the site this page come from is fully coded this way. Changing the paradigm of the whole thing is not an option.
I have read and read again the links on GridView updating. I am not new to this but I cannot make the GridView Update work. Can you have a look?
<asp:SqlDataSource ID="sds_Drivers" runat="server" ConnectionString="<%$ ConnectionStrings:ThinairConnectionString %>" SelectCommand="SELECT [User_Id], [User_Active], [User_Reference], [User_Name], [User_Login], [User_Password] FROM [Users] WHERE ([User_Acct_Number] = #User_Acct_Number) ORDER BY [User_Name]" UpdateCommand="UPDATE [Users] SET [User_Active] = #User_Active, [User_Reference] = #User_Reference, [User_Name] = #User_Name, [User_Login] = #User_Login, [User_Password] = #User_Password WHERE ([User_Id] = #User_Id)" OnUpdating="sds_Drivers_Updating">
<SelectParameters>
<asp:SessionParameter Name="User_Acct_Number" SessionField="Acct_Number" Type="String" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="User_Active" Type="Int32" />
<asp:Parameter Name="User_Reference" Type="String" />
<asp:Parameter Name="User_Name" Type="String" />
<asp:Parameter Name="User_Login" Type="String" />
<asp:Parameter Name="User_Password" Type="String" />
<asp:Parameter Name="User_Id" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
</p>
<p>
<asp:GridView ID="gv_Drivers" runat="server"
Width="100%"
AllowSorting="True"
AutoGenerateColumns="False"
DataKeyNames="User_Id"
ConvertEmptyStringToNull="False"
DataSourceID="sds_Drivers"
CellSpacing="2"
CellPadding="2"
HeaderStyle-ForeColor="Black"
HeaderStyle-Wrap="true">
<Columns>
<asp:CommandField EditText="Edit" ShowEditButton="True" ValidationGroup="Group3" />
<asp:BoundField DataField="User_Id" HeaderText="User Id" ReadOnly="true" SortExpression="User_Id" />
<asp:BoundField DataField="User_Active" HeaderText="1 = Active / 0 = Inactive" SortExpression="User_Active" />
<asp:BoundField DataField="User_Reference" HeaderText="Your Reference" SortExpression="User_Reference" />
<asp:BoundField DataField="User_Name" HeaderText="User Name" SortExpression="User_Name" />
<asp:BoundField DataField="User_Login" HeaderText="User Login" SortExpression="User_Login" />
<asp:BoundField DataField="User_Password" HeaderText="User Password" SortExpression="User_Password" />
</Columns>
<EmptyDataTemplate>
No Drivers Loaded
</EmptyDataTemplate>
</asp:GridView>
What I tried for debugging in code behind:
protected void sds_Drivers_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
foreach (SqlParameter p in e.Command.Parameters)
{
Response.Write(p.ParameterName + ": " + p.Value + "<br />");
}
}
The good news is I have values. The bad news is that these are not the new values in the edit fields.
What did I miss?
Thanks in Advance!
You can try this:
protected void sds_Drivers_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
foreach (SqlParameter p in e.Command.Parameters)
{
Response.Write(p.ParameterName + ": " + p.NewValues + "<br />");
}
}
Sorry for repeating the question but I have searched almost all the questions on stackoverflow but didn't find any solution. Im implementing a gridview where im using a WHERE clause, but got in gridview.
here is the code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDS1">
<Columns>
<asp:BoundField DataField="alert_title" HeaderText="alert_title"
SortExpression="alert_title" />
<asp:BoundField DataField="alert_desc" HeaderText="alert_desc"
SortExpression="alert_desc" />
<asp:BoundField DataField="alert_deadline" HeaderText="alert_deadline"
SortExpression="alert_deadline" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDS1" runat="server"
ConnectionString="<%$ ConnectionStrings:SQL %>"
SelectCommand="SELECT [alert_title], [alert_desc], [alert_deadline] FROM [Table_Alerts] WHERE [alert_owner] = #alert_owner ">
<SelectParameters>
<asp:Parameter Name="alert_owner" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
aspx.cs file
protected void Page_Load(object sender, EventArgs e)
{
string Value = "muneeb";
//Parameter par = new Parameter("#alert_owner", DbType.String,Value);
//SqlDS1.SelectParameters.Add(par);
SqlDS1.SelectParameters["#alert_owner"].DefaultValue = "muneeb";
}
after implementing this got an expection at
SqlDS1.SelectParameters["#alert_owner"].DefaultValue = "muneeb";
can some please tell me where I went wrong? or how can i fix it. Thanks in Advance
I have DetailsView nested in GridView, and I can't figure out how to pass values(like ID of item in GridView and value from session) to parameters for insert method.
<asp:DetailsView ID="DetailsViewPostLikes" runat="server"
AutoGenerateRows="false" DataSourceID="odsPostLikes"
DataKeyNames="id" GridLines="None">
<Fields>
<asp:CommandField ShowInsertButton="true" InsertText="Like" newtext="Like" />
<asp:TemplateField HeaderText="" SortExpression="Nickname">
<ItemTemplate>
<asp:Label id="nicknamelikesCount" runat="server" Text='<%# Bind("LikeCount") %>'></asp:Label> people likes this.
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
<asp:ObjectDataSource ID="odsPostLikes" runat="server"
TypeName="SocWebApp.Database.PostLikeTable"
SelectMethod="Select" InsertMethod="Insert" UpdateMethod="Update">
<SelectParameters>
<asp:Parameter Name="postId" Type="Int32" />
</SelectParameters>
<InsertParameters>
<asp:Parameter Name="postId" Type="Int32" />
<asp:SessionParameter Name="userId" SessionField="User_id" Type="Int32" />
</InsertParameters>
</asp:ObjectDataSource>
I've tried to do this same way as for select parameter like this:
protected void posts_ItemDatabound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)//(GridView)e.Row.FindControl("odsComments") != null)
{
ObjectDataSource s1 = (ObjectDataSource)e.Row.FindControl("odsComments");
s1.SelectParameters["postId"].DefaultValue = DataBinder.Eval(e.Row.DataItem, "Id").ToString();
ObjectDataSource s2 = (ObjectDataSource)e.Row.FindControl("odsPostLikes");
s2.InsertParameters["postId"].DefaultValue = DataBinder.Eval(e.Row.DataItem, "Id").ToString();
ObjectDataSource s3 = (ObjectDataSource)e.Row.FindControl("odsPostLikes");
s3.InsertParameters["userId"].DefaultValue = Session["User_id"].ToString();
}
}
but only userId parameter value is set(from Session), postId is always 0.
What is the proper solution?
Thank you.
I've found the solution:
<asp:DetailsView ID="DetailsViewPostLikes" runat="server"
AutoGenerateRows="false" DataSourceID="odsPostLikes"
DataKeyNames="id" GridLines="None" OnDataBound="postLikeInsert_DataBound" OnItemCommand="postLikeInsert_ItemCommand">
<Fields>
<asp:CommandField ShowInsertButton="false" InsertText="Like" newtext="Like" />
<asp:TemplateField HeaderText="" SortExpression="Nickname">
<ItemTemplate>
<asp:LinkButton ID="Like" runat="server" CommandName="Insert" Text="Like" />
<asp:Label id="likesCount" runat="server" Text='<%# Bind("LikeCount") %>'></asp:Label> people likes this.
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
<asp:ObjectDataSource ID="odsPostLikes" runat="server"
TypeName="SocWebApp.Database.PostLikeTable"
SelectMethod="Select" InsertMethod="Insert" UpdateMethod="Update">
<SelectParameters>
<asp:Parameter Name="postId" Type="Int32" />
</SelectParameters>
<InsertParameters>
<asp:Parameter Name="postId" Type="Int32" />
<asp:SessionParameter Name="userId" SessionField="User_id" Type="Int32" />
</InsertParameters>
</asp:ObjectDataSource>
code-behind:
protected void postLikeInsert_DataBound(object sender, EventArgs e)
{
DetailsView d = (DetailsView)sender;
GridViewRow row = (GridViewRow)d.NamingContainer;
int idx = row.RowIndex;
GridView grid = (GridView)row.NamingContainer;
string strGoalIndicatorID = grid.DataKeys[idx]["id"].ToString();
LinkButton b = (LinkButton)d.FindControl("Like");
b.CommandArgument = strGoalIndicatorID;
}
protected void postLikeInsert_ItemCommand(object sender, DetailsViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
DetailsView d = (DetailsView)sender;
d.ChangeMode(DetailsViewMode.Insert);
ObjectDataSource o = (ObjectDataSource)d.NamingContainer.FindControl("odsPostLikes");
o.InsertParameters["postId"].DefaultValue = e.CommandArgument.ToString();
}
}
when data bound, it will find the button and set his command argument to id item of parent gridview, then after hitting the button, insert parameter is set based on that command argument
I am trying to delete a row from gridview on rowdataBound() event but get Procedure or function delete_row has too many arguments specified.
Below is the code
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row != null) && (e.Row.RowType == DataControlRowType.DataRow))
{
for (int i = 0; i < GridView1.Rows.Count; i++ )
{
GridView1.Rows[i].Attributes["style"] += "cursor: pointer; cursor: hand;";
if (GridView1.DataKeys[i].Values[1].ToString() != "broken")
GridView1.Rows[i].Attributes["onclick"] =
"window.open('" + GridView1.DataKeys[i].Values[0].ToString() + "','open_window', 'menubar, toolbar, location, directories, status, scrollbars, resizable, dependent, width=640, height=480, left=0, top=0')";
else
{
GridView1.DeleteRow(i);
}
}
}
HTML mark up is below, I have 3 DataKeyNames declared is that the problem
<asp:HiddenField ID="hiddenField1" runat="server" Value="" />
<br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:User42ConnectionString %>"
SelectCommand="lsp_show_by_letter" onselecting="SqlDataSource1_Selecting"
SelectCommandType="StoredProcedure" DeleteCommand="delete_row"
DeleteCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="hiddenField1" DefaultValue=" "
Name="letter" PropertyName="Value" Type="String" />
</SelectParameters>
<DeleteParameters>
<asp:ControlParameter Name="link_Id" ControlID="hiddenField1" PropertyName="Value" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>
</div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" onrowdatabound="GridView1_RowDataBound"
DataKeyNames="link_url,link_description,link_id">
<Columns>
<asp:BoundField DataField="link_display_string"
HeaderText="link_display_string" SortExpression="link_display_string" />
<asp:BoundField DataField="link_url"Visible="False" />
<asp:BoundField DataField="link_description" Visible="False" />
<asp:BoundField DataField="link_id" ReadOnly="true" Visible="False" />
</Columns>
</asp:GridView>
Delete row stored procedure is
`ALTER PROCEDURE dbo.delete_row #link_Id int AS BEGIN DELETE FROM [links] WHERE ([link_id] = #link_Id) END`
It's because your hiddenfiled is not bound to SqlDataSource and so it passes empty or null value to delete_row procedure. Since you are bounding your SQLDataSource directly to datagridview, you need to bound hideenfiled with selected row value of datagridview. This should help you trying few options but this is your base problem.