Displaying Grid View on Page Load - c#

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();

Related

ASP.NET SQLDataSource SelectParameters not set correctly

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.

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 UpdateCommand Being Called Twice

I have a GridView that is bound to a SqlDataSource. I am running into issues with the UpdateCommand executing, it seems to be executing twice. When I step through the code in the gvChecklist_RowUpdating event, I see everything runs properly and the stored procedure is executed. I have verified the stored procedure works properly since there is a new record in the db table. When this event exits though, I get the following error:
Procedure or function usp_TestLogInsert has too many arguments
specified.
I see that the Updating event on the datasource is being called after the RowUpdating event. I have tried to cancel this event to prevent the multiple update attempts, but then nothing happens and the GridView stays in edit mode.
ASP Code
<asp:UpdatePanel ID="upGridView" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gvChecklist" runat="server"
AutoGenerateColumns="false" DataSourceID="dsChecklist"
AutoGenerateEditButton="true"
onrowupdating="gvChecklist_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server"
Text='<%#Eval("Status") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddStatus" runat="server"
DataTextField="Status"
DataValueField="ID"
DataSourceID="dsStatus" />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Division"
HeaderText="Division"
readonly="true" />
<asp:BoundField DataField="Application"
HeaderText="Application"
readonly="true" />
<asp:BoundField DataField="Task"
HeaderText="Task"
readonly="true" />
<asp:BoundField DataField="TestedBy"
HeaderText="Tested By"
readonly="true"/>
<asp:BoundField DataField="Notes"
HeaderText="Notes"
ReadOnly="false"/>
<asp:BoundField DataField="JiraTicket"
HeaderText="JIRA Ticket"
readonly="false" />
<asp:BoundField DataField="ID" />
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="gvChecklist" />
</Triggers>
</asp:UpdatePanel>
</td>
</tr>
</table>
<asp:SqlDataSource ID="dsChecklist"
SelectCommand=" SELECT l.ID, d.division, c.Context AS Application, t.Task, l.TestedBy, l.Notes, l.JiraTicket, s.Status
FROM Automation.manual.Tests t
OUTER APPLY
(SELECT TOP 1 *
FROM Automation.manual.TestLog l
WHERE l.TestID = t.ID
ORDER BY l.Date DESC) l
INNER JOIN Automation.dbo.Context c ON c.ID = t.Context
INNER JOIN Automation.dbo.Division d ON d.ID = t.Division
LEFT OUTER JOIN Automation.manual.Status s ON s.ID = l.Status"
runat="server"
ConnectionString="<%$ ConnectionStrings:AutomationDBConnectionString %>"
onupdating="dsChecklist_Updating" >
<UpdateParameters>
<asp:Parameter Name="Status" DbType="Int32" />
<asp:Parameter Name="TestID" DbType="Int32" />
<asp:Parameter Name="TestedBy" DbType="String" />
<asp:Parameter Name="Notes" DbType="String" />
<asp:Parameter Name="JiraTicket" DbType="String" />
<asp:Parameter Name="Build" DbType="String" />
</UpdateParameters>
</asp:SqlDataSource>
C#
protected void gvChecklist_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SQLConnections sql = new SQLConnections();
SqlDataSource dsChecklist = (SqlDataSource)LoginView1.FindControl("dsChecklist");
var dd = (DropDownList)gvChecklist.Rows[e.RowIndex].FindControl("ddStatus");
var status = dd.SelectedValue;
var testID = sql.SQLSelectSingle(String.Format("SELECT ID FROM Automation.manual.Tests WHERE Task = '{0}'", (String)e.OldValues["Task"]), "pwautosql01");
string user = Page.User.Identity.Name;
string notes = (String)e.NewValues["Notes"];
string jira = (String)e.NewValues["JiraTicket"];
var dbID = e.NewValues["ID"];
string build = "TODO";
if (dbID == null) //Record does not exist in TestLog, INSERT a new one
{
dsChecklist.UpdateCommand = "[Automation].[manual].[usp_TestLogInsert]";
dsChecklist.UpdateCommandType = SqlDataSourceCommandType.StoredProcedure;
dsChecklist.UpdateParameters["Status"].DefaultValue = status;
dsChecklist.UpdateParameters["TestID"].DefaultValue = testID;
dsChecklist.UpdateParameters["TestedBy"].DefaultValue = user;
dsChecklist.UpdateParameters["Notes"].DefaultValue = notes;
dsChecklist.UpdateParameters["JiraTicket"].DefaultValue = jira;
dsChecklist.UpdateParameters["Build"].DefaultValue = build;
gvChecklist.DataBind();
}
//else //Record already exists in TestLog. UPDATE
//{
//TODO
//}
}
EDIT: I used the SQL Profiler to see what parameters are being sent in the stored procedure. Even though the INSERT occurs and a new record is created, an extra parameter called ID is being sent. I never explicitly send this parameter, but it seems that it is created since I have a BoundField called ID in my GridView.
To build on the original question, is there a way to make the UpdateCommand ignore this BoundField so it does no automatically use it as a parameter?
After using the SQL Profiler, I saw that BoundField ID was being added as an UpdateCommand Parameter implicitly. Changing this field to a TemplateItem fixes this issue.
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="tbId" Text='<%#Eval("ID") %>' ReadOnly="true" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>

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

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