ASP.NET SQLDataSource SelectParameters not set correctly - c#

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.

Related

Stored procedure expects parameter that was not supplied

I have a SqlDataSource connected to a GridView and I am trying to get the edit working correctly, but with everything I try I still get that parameters are not supplied.
I have tried naming the parameters with and without the '#', it seems to make no difference. As you can see in the below image, the update parameters exist and even have values!
Example image:
ASPX markup:
<asp:GridView runat="server" ID="JobGV" DataSourceID="JobApprovalsDS"
AutoGenerateColumns="False" AutoGenerateEditButton="true"
OnRowCommand="JobGV_OnRowCommand" OnRowUpdating="JobGV_OnRowUpdating">
<Columns>
<asp:BoundField HeaderText="Function" DataField="FunDesc" ReadOnly="true"/>
<asp:BoundField HeaderText="Employee" DataField="EmpName" ReadOnly="true"/>
<asp:TemplateField>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="ddlEmps" SelectedValue='<%# Eval("appEmpID")%>' DataSourceID="EmpDS" DataTextField="EmpName" DataValueField="EmpID" />
<asp:Label runat="server" ID="data" Text='<%# Eval("appBusinessUnit") +";" + Eval("appFunctID") %>' Visible="False"></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("EmpName") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="JobApprovalsDS" runat="server"
ConnectionString="<%$ ConnectionStrings:JobClose %>"
SelectCommand="up_JobApprovalsSelect"
SelectCommandType="StoredProcedure"
UpdateCommand="up_JobApprovalsUpdate">
<SelectParameters>
<asp:Parameter Name="ShowAll" DefaultValue="1" />
<asp:Parameter Name="AllPhases" DefaultValue="1" />
<asp:ControlParameter Name="BusinessUnit" ControlID="ddlEditJob" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="#BusinessUnit" Type="String"/>
<asp:Parameter Name="#FunctID" Type="Int32"/>
<asp:Parameter Name="#EmpID" Type="Int32"/>
<asp:Parameter Name="#UpdateDate" Type="DateTime"/>
</UpdateParameters>
</asp:SqlDataSource>
C#:
protected void JobGV_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Update"))
{
int empid = 0;
string[] data;
int index = int.Parse(e.CommandArgument.ToString());
GridViewRow row = JobGV.Rows[index];
DropDownList ddlemp = (DropDownList) row.FindControl("ddlEmps");
empid = int.Parse(ddlemp.SelectedValue);
Label lbl = (Label) row.FindControl("data");
data = lbl.Text.Split(';');
JobApprovalsDS.UpdateParameters["#BusinessUnit"].DefaultValue = data[0];
JobApprovalsDS.UpdateParameters["#FunctID"].DefaultValue = data[1];
JobApprovalsDS.UpdateParameters["#EmpID"].DefaultValue = empid.ToString();
//JobApprovalsDS.UpdateParameters.Add("BusinessUnit", data[0]);
//JobApprovalsDS.UpdateParameters.Add("FunctID", data[1]);
//JobApprovalsDS.UpdateParameters.Add("EmpID", empid.ToString());
}
}
protected void JobGV_OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
JobApprovalsDS.Update();
}
Are you talking about the update process??
Well, in your SqlDataSource, you're not specifying that the UpdateCommand is talking to a stored procedure... you need to specify the UpdateCommandType, too! (not just the SelectCommandType)
<asp:SqlDataSource ID="JobApprovalsDS" runat="server"
ConnectionString="<%$ ConnectionStrings:JobClose %>"
SelectCommand="up_JobApprovalsSelect"
SelectCommandType="StoredProcedure"
UpdateCommand="up_JobApprovalsUpdate"
UpdateCommandType="StoredProcedure" > **** this is missing from your code!

sqldatasource update command not working and no SQL error

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.

Nested DetailsView insert method's parameters

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

Displaying Grid View on Page Load

I have a grid view with a stored procedure set up in SQL.I have three controls 2 dropdown list's and a texbox with jQuery Date picker.My problem is that the gridview isn't showing on pageload. However when I start adding the controls the gridview is suddenly displayed. From debugging, I have speculated that the textbox with the jQuery datepicker does not pass the NULL value to the stored procedure specified, though I am still wondering if it is the cause.This is the code..
Aspx Code:
<div class="datarange">
<asp:DropDownList ID="categoryDDL" AutoPostBack="true" AppendDataBoundItems="true" runat="server">
<asp:ListItem Text="Select Category" Value=" " />
</asp:DropDownList>
<asp:DropDownList ID="brokerDDL" AutoPostBack="true" runat="server"></asp:DropDownList>
<asp:TextBox ID="openDate" AutoPostBack="true" runat="server"></asp:TextBox>
</div>
<br />
<%-- SQL DATA SOURCE PARAMETERS --%>
<asp:SqlDataSource ID="SqlRAListings" runat="server" ConnectionString="<%$ ConnectionStrings:kmc_SalesPipelineConnectionString %>" SelectCommand="RecentlyAddedListings" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="categoryDDL" Name="Category" PropertyName="SelectedValue" Type="String" DefaultValue=" " />
<asp:ControlParameter ControlID="brokerDDL" Name="Broker" PropertyName="SelectedValue" Type="String" DefaultValue=" Select Employee" />
<asp:ControlParameter ControlID="openDate" Name="OpenDate" PropertyName="Text" Type="DateTime" DefaultValue="" />
</SelectParameters>
</asp:SqlDataSource>
<%-- END OF SQL DATA SOURCE PARAMETERS --%>
<%-- GRIDVIEW FOR DISPLAYING RECENTLY ADDED LISTINGS --%>
<asp:GridView ID="ralGridView" runat="server" AllowSorting="True" AutoGenerateColumns="False" OnSelectedIndexChanged="ralGridView_SelectedIndexChanged">
<Columns>
<asp:TemplateField HeaderText="Opportunity">
<ItemTemplate>
<a href="/management/opportunity.aspx?id=<%# Eval("ID") %>" target="_blank">
<%# Eval("Opportunity").ToString() != "" ? Eval("Opportunity") : "Opportunity" %>
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID"
SortExpression="ID" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="Category" HeaderText="Category"
SortExpression="Category" />
<asp:BoundField DataField="Contact Name" HeaderText="Contact Name"
SortExpression="Contact Name" />
<asp:BoundField DataField="Employee" HeaderText="Employee" SortExpression="Employee" />
<asp:BoundField DataField="Open Date" HeaderText="Open Date" SortExpression="Open Date" />
<asp:TemplateField HeaderText="Opportunity from">
<ItemTemplate>
<%# Eval("LeadID").ToString().Length > 0 == true ? "Lead System" : "Personal Lead" %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDbRAListings" runat="server" ConnectionString="<%$ ConnectionStrings:kmc_SalesPipelineConnectionString %>" SelectCommand="RecentlyAddedListings" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="categoryDDL" Name="Category" PropertyName="SelectedValue" Type="String" />
<asp:ControlParameter ControlID="brokerDDL" Name="Broker" PropertyName="SelectedValue" Type="String" />
<asp:ControlParameter ControlID="openDate" Name="OpenDate" PropertyName="Text" Type="DateTime" />
</SelectParameters>
</asp:SqlDataSource>
<%-- END OF GRID VIEW --%>
</form>
<script type="text/javascript">
$(function () {
var dates = $("#openDate").datepicker({
defaultDate: "+1w",
changeMonth: false,
numberOfMonths: 1
});
});
</script>
C# Code:
namespace KMCWebLMS
{
public partial class RecentlyAssignedLead : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
fillCategoryDropDown();
fillBrokerDropDown();
}
else
{
ralGridView.DataSource = SqlDbRAListings;
ralGridView.DataBind();
}
}
public void fillCategoryDropDown()
{
DataTable categories = new DataTable();
string command = #"SELECT LeadCategory FROM LeadCategory ORDER BY LeadCategory";
ConnectSQL cmd = new ConnectSQL();
SqlDataAdapter adapter = new SqlDataAdapter(cmd.configureSQL(command));
adapter.Fill(categories);
try
{
categoryDDL.DataSource = categories;
categoryDDL.DataTextField = "LeadCategory";
categoryDDL.DataValueField = "LeadCategory";
categoryDDL.DataBind();
}
catch
{
}
}
public void fillBrokerDropDown()
{
DataTable employees = new DataTable();
string command = #"SELECT TOP 100 [Emp_Name] FROM [kmc_SalesPipeline].[dbo].[vwEmployees] ORDER BY Emp_Name";
ConnectSQL cmd = new ConnectSQL();
SqlDataAdapter adapter = new SqlDataAdapter(cmd.configureSQL(command));
adapter.Fill(employees);
try
{
brokerDDL.DataSource = employees;
brokerDDL.DataTextField = "Emp_Name";
brokerDDL.DataValueField = "Emp_Name";
brokerDDL.DataBind();
}
catch
{
}
}
protected void ralGridView_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
But from your code behind , it seems you're populating the gridview only in a postback.
For PageLoad , you're only populating the dropdowns.
Shouldn't this code come
ralGridView.DataSource = SqlDbRAListings;
ralGridView.DataBind();
inside
if (!Page.IsPostBack)
I have found the solution to the problem. To do this, I declared the parameters required for the stored procedure in the Code Behind and set it there accordingly.
//STORED PROCEDURE PARAMETERS
cmd.Parameters.AddWithValue("#OpenDate", OpenDate);
cmd.Parameters.AddWithValue("#Broker", broker);
cmd.Parameters.AddWithValue("#Category", category);
The program will then display the default value on page_load displaying all the data in the gridview. On postback, the specified parameters will be set to the values that are currently stored in the specific control parameters accordingly.
broker = brokerDDL.SelectedValue;
category = categoryDDL.SelectedValue;
ralGridView.DataSource = CreateRecentlyAddedTable();
ralGridView.DataBind();

Delete a row from gridview

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.

Categories

Resources