Code behind in aspx sql - c#

May I know how could I pass the value of driver from code behind and throw into the query in aspx file ?
Here is my aspx part:
<asp:SqlDataSource ID="cs_sc" runat="server"
ConnectionString="<%$ ConnectionStrings:MIMConnectionString %>"
SelectCommand="SELECT * FROM [Cash_Sales] WHERE [driver] = #driver">
<SelectParameters>
<asp:Parameter Name="driver" Direction="Input" Type="String" />
</SelectParameters></asp:SqlDataSource>
code behind:
protected void Button1_Click(object sender, EventArgs e)
{
driver = driverUpdateBox.SelectedItem.Text;
}

cs_sc.SelectParameters["driver"].DefaultValue = driverUpdateBox.SelectedItem.Text;

Have you tried something like this:
SelectCommand="SELECT * FROM [Cash_Sales] WHERE [driver] = <%$ this.driver %>">

SqlDataSource has SelectParameters property, use it like this :
protected void Button1_Click(object sender, EventArgs e)
{
cs_sc.SelectParameters["driver"] = driverUpdateBox.SelectedItem.Text;
}

Related

Changing SqlDataSource SelectCommand and SelectParameter with a button

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString9 %>" ProviderName="<%$ ConnectionStrings:ConnectionString9.ProviderName %>" SelectCommand="SELECT * FROM [Orders] WHERE ([oStatus] = ?)">
<SelectParameters>
<asp:Parameter DefaultValue="CheckedOut" Name="oStatus" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Above is the code for the SqlDataSource. What I am trying to do is to add a button which will help me add an additional WHERE condition into SelectCommand and add the SelectParameters for the added condition.
Button
<asp:Button runat="server" text="filter record" ID="filterbutton" OnClick="filterbutton_Click"/>
What I want the SelectCommand to look like when button is clicked
SelectCommand="SELECT * FROM [Orders] WHERE ([oStatus] = ?) AND ([oDelivery_Status] = ?)">
Question is it is possible to add more than 1 SelectParameters? And is it possible to do so with a button OnClick method? If not, are there any other solutions/methods? Thank you in advance.
You need to set both Parameters which you want in your SelectCommand like this:
protected void filterbutton_Click(object sender, EventArgs e)
{
string stroStatus = "";
string stroDelivery_Status = "";
SqlDataSource1.SelectParameters["oStatus"].DefaultValue = stroStatus;
Parameter pm = SqlDataSource1.SelectParameters["oDelivery_Status"];
if (!SqlDataSource1.SelectParameters.Contains(pm))
{
SqlDataSource1.SelectParameters.Add("oDelivery_Status",
stroDelivery_Status);
}
SqlDataSource1.SelectCommand = "SELECT * FROM [Orders] WHERE ([oStatus] = #oStatus) AND ([oDelivery_Status] = #oDelivery_Status)"
}

Delete command not firing on post back, asp.net repeater

I have a page that contains a data repeater which in turn contains a button that is meant to delete a delete a record from an SQL database. When this button is clicked I receive the following error: Procedure or function 'usp_setKS3_DeleteAssessment' expects parameter '#intAssessmentId', which was not supplied.
If I comment out the KS3_DataSource_Assessment.Delete(); line in the code behind the page loads without error and displays the message, but does not delete the record (which I expect as the line was commented out). I have no idea what to do to make this work... any ideas?
ASP.net
<asp:SqlDataSource ID="KS3_DataSource_Assessment" runat="server" ConnectionString="<%$ ConnectionStrings:sqlWriter %>" ProviderName="System.Data.SqlClient" SelectCommandType="StoredProcedure" SelectCommand="usp_getKS3_ManageAssessments" OnSelected="KS3_DataSource_Assessment_Selected" DeleteCommand="usp_setKS3_DeleteAssessment">
<SelectParameters>
<asp:ControlParameter ControlID="KS3_DropDown_ACYear" PropertyName="SelectedValue" Name="intACYearId" Type="Int32" />
<asp:ControlParameter ControlID="KS3_DropDown_Subject" PropertyName="SelectedValue" Name="intSubjectId" Type="Int32" />
<asp:ControlParameter ControlID="KS3_DropDown_Year" PropertyName="SelectedValue" Name="intYearGroup" Type="Int32" />
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="intAssessmentId" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>
<asp:Repeater runat="server" ID="KS3_Repeater_Assessments" EnableViewState="true" DataSourceID="KS3_DataSource_Assessment" OnItemDataBound="KS3_Repeater_Assessments_ItemDataBound">
<ItemTemplate>
<!-- Assessments -->
<asp:Table runat="server" ID="KS3_Table_Assessments" CssClass="width100pc">
<asp:TableRow CssClass="SectionSubHeader">
<asp:TableCell><%# Eval("txtAssessmentTitle").ToString() %></asp:TableCell>
<asp:TableCell CssClass="width25px alignCenter alignVerticalMiddle" RowSpan="2"><asp:ImageButton SkinID="imgButtonDelete" runat="server" ID="KS3_Button_DeleteAssessment" OnCommand="KS3_Button_DeleteAssessment_Command" CommandArgument='<%# Eval("intAssessmentID").ToString() %>' OnClientClick="return confirm('Are you sure you want to delete this assessment?\n\nOnce deleted all data is lost.');" /></asp:TableCell>
<asp:TableCell CssClass="width25px alignCenter alignVerticalMiddle" RowSpan="2">Up</asp:TableCell>
<asp:TableCell CssClass="width25px alignCenter alignVerticalMiddle" RowSpan="2">Down</asp:TableCell>
</asp:TableRow>
<asp:TableRow CssClass="BackgroundBlack fontStyleItalic">
<asp:TableCell><%# Eval("txtAssessmentDescription").ToString() %></asp:TableCell>
</asp:TableRow>
</asp:Table>
<!-- Columns -->
<asp:SqlDataSource ID="KS3_DataSource_Columns" runat="server" ConnectionString="<%$ ConnectionStrings:sqlWriter %>" ProviderName="System.Data.SqlClient" SelectCommandType="StoredProcedure" SelectCommand="usp_getKS3_ManageAssessments">
<SelectParameters>
<asp:Parameter Name="intACYearId" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</ItemTemplate>
</asp:Repeater>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
}
protected void KS3_Button_SelectSubject_Click(object sender, EventArgs e)
{
if (KS3_DropDown_Subject.SelectedIndex == 0) { DisplayMessage("Validation Error", "Please select a subject from the list below.", "error"); KS3_Panel_DataToManage.Visible = false; }
else if (KS3_DropDown_Year.SelectedIndex == 0) { DisplayMessage("Validation Error", "Please select a year group from the list below.", "error"); KS3_Panel_DataToManage.Visible = false; }
else
{
//No errors detected, start data display
Master.systemMessageHide();
KS3_Panel_DataToManage.Visible = true;
//Update display
KS3_Label_Title.Text = KS3_DropDown_Subject.SelectedItem.Text.Trim() + " - " + KS3_DropDown_Year.SelectedItem.Text.Trim();
//Bind the new data to the repeater
KS3_Repeater_Assessments.DataBind();
}
}
public void DisplayMessage(string title, string message, string type)
{
Master.systemMessageShow(title, message, type);
}
protected void KS3_DataSource_Assessment_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
if (e.AffectedRows < 1) { KS3_Panel_NoAssessments.Visible = true; }
else { KS3_Panel_NoAssessments.Visible = false; }
}
protected void KS3_Button_DeleteAssessment_Command(object sender, CommandEventArgs e)
{
KS3_Label_Title.Text = "DataSubmitted";
KS3_DataSource_Assessment.DeleteParameters["intAssessmentId"].DefaultValue = e.CommandArgument.ToString();
Trace.Write("Item Value: " + e.CommandArgument.ToString());
KS3_DataSource_Assessment.Delete();
KS3_Repeater_Assessments.DataBind();
DisplayMessage("Assessment Delete", "The selected assessment has been deleted and all associated data has been removed.", "success");
}
It looks that you are missing this attribute of the data source control:
DeleteCommandType="StoredProcedure"
Default value is Text, which makes control think that the command provided is an SQL statement. Since you are using stored procedure, this is not the behavior you want.

Asp.Net GridView Datasource in aspx page

In default.aspx.cs , i defined a public variable. = my_id
And i can use this variable in my aspx page.
But i can't use in GridView DataSourceQuery.
My gridview's datasource code : ( in aspx )
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:aspnetdbConnectionString %>" SelectCommand="SELECT [mus_ad], [marka], [model], [durum] FROM [servis_kayitlari] WHERE [kullanici_id] LIKE '<%= my_id ;%>'">
</asp:SqlDataSource>
After this datasource query , gridview comes null. What is the problem in this query ?
You should use parameterized query(see Using Parameters with the SqlDataSource Control for reference) and assign parameter value in SqlDataSource.Selecting event:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:aspnetdbConnectionString %>"
SelectCommand="SELECT [mus_ad], [marka], [model], [durum] FROM [servis_kayitlari] WHERE [kullanici_id] LIKE #my_id"
OnSelecting="SqlDataSourceSelectingEventHandler">
<SelectParameters>
<asp:Parameter Name="my_id" Type="Int32" DefaultValue="0" />
</SelectParameters>
</asp:SqlDataSource>
And event handler:
public void SqlDataSourceSelectingEventHandler(object sender, SqlDataSourceSelectingEventArgs e)
{
SqlDataSource1.SelectParameters["my_id"].DefaultValue = this.my_id;
}
As suggested in other answer, you should rather choose to use parametrized query but per your posted query, the issue is in binding variable with LIKE. You need to remove the ; in <%= my_id ;%>. Your query should look like
SELECT [mus_ad], [marka], [model], [durum] FROM [servis_kayitlari] WHERE [kullanici_id] LIKE '<%= my_id %>'"

Code for update and delete a row in grid view

what is the code for updating and saving from grid view data directly in a web form.This is the code i have.Help me out for delete record and update record.
protected void CancelRecord(object sender, GridViewCancelEditEventArgs e)
{
gridRegistrationTableDetails.EditIndex = -1;
BindData();
}
protected void EditRecord(object sender, GridViewEditEventArgs e)
{
gridRegistrationTableDetails.EditIndex = e.NewEditIndex;
BindData();
}
protected void UpdateRecord(object sender, GridViewUpdateEventArgs e)
{
}
protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
{}
i need to edit the four columns Emp name,Emp address,emp dept,emp mail.emp ID is the primary key.pls help me on this..
If you are using database ,then create functions for Update and Delete
Eg:
Public void Update(DataClass dataclass){...}
public void Delete(int Id){...}
Write these following code in your apsx page
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
</Columns>
</asp:GridView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
DataObjectTypeName="DataClass" DeleteMethod="Delete"
TypeName="YourServiceClass" UpdateMethod="Update">
<DeleteParameters>
<asp:Parameter Name="id" Type="Int32" />
</DeleteParameters>
</asp:ObjectDataSource>
place this code in gridview Rowdeleting event
GridViewRow row = (GridViewRow)gv_Type.Rows[e.RowIndex];
d.con_Open();
SqlCommand cmd = new SqlCommand("Delete from tbl_Category where Catno=" + Convert.ToInt32(gv_Type.Rows[e.RowIndex].Cells[1].Text) + "", d.con);
cmd.ExecuteNonQuery();
d.con_Close();

How to embed variable value in sqldatasource session parameter in c#

I want to question how to embed variable value in sqldatasource session parameter in c#. This is mycode:
default.aspx:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Ora2011 %>"
ProviderName="<%$ ConnectionStrings:Ora2011.ProviderName %>"
SelectCommand="SELECT ID, CATEGORY_NAME FROM (:INVENT_CATEGORY)">
<SelectParameters>
<asp:SessionParameter Name="INVENT_CATEGORY" SessionField="INVENT_CATEGORY" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
C#:
protected void Page_Load(object sender, EventArgs e)
{
string table = "V_INVENTORY"
Session["INVENT_CATEGORY"] = table;
}
When i run this program, i get error "invalid table name". Why i can't embed variable into sqldatasource from session parameter. Thanks for your help
Your issue isn't with the Session parameter... The problem is that you are trying to specify the table-name via a parameter -- which I'm pretty sure is not supported. You'd have to build the query string yourself in your code-behind to do what you are trying to do.
I'm not sure why you are storing the table name in Session, but an example of setting the sql select in code-behind would be...
Markup:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Ora2011 %>"
ProviderName="<%$ ConnectionStrings:Ora2011.ProviderName %>"
</asp:SqlDataSource>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
string table = (string)(Session["INVENT_CATEGORY"] ?? "V_INVENTORY");
SqlDataSource1.SelectCommand = "SELECT ID, CATEGORY_NAME FROM " + table;
}
You must make sure that the session value for the table name can only contain valid values, or there is a danger of SQL Injection attacks.

Categories

Resources