Quantcast
Channel: DataSource Controls - SqlDataSource, ObjectDataSource, etc.
Viewing all 956 articles
Browse latest View live

ListView and DataPager

$
0
0

Hi:

I combine listview and datapage, so each time when listview data binding

then datapager will show didfferent page numbers, 

however if I set listview.datasource=null, and then databind, 

how to make the page number of datapager disappear. 

Any suggestion is appreciated, thanks.


Conditional SelectCommand

$
0
0

I use the following SELECTCOMMAND to retrieve data based on two incoming QueryString values.

"ResultIn" is a value that the user selects on the inquiry screen... that value can be, for example 1, 2, 3.... the resulting search will return records matching containing the provided Result value.

My question is this: I would like to craft a query that can also return results matching "ALL" Result values 1,2 AND (Using, e.g. a Wild Card, if the Result value provided is for example  "4", which would mean return ALL  records.

Is there a possibility of using a Multiple  or conditional SelectCommand or using CASE in some manner ?

Thank you in advance!

<asp:SqlDataSourceID="SqlDataSourceMulti"runat="server"
 ConnectionString="<%$ ConnectionStrings:connString %>"                         
    SelectCommand="SELECT 
                                FD.[ContentID] ,
                                FD.[FreezerID] ,
                                FD.[Accession] ,
                                FD.[DateInStorage] ,
                                FD.[BarCode] ,
                                FD.[SampleType] ,
                                FD.[Media] , 
                                FD.[Panel] , 
                                FD.[PatientLName] ,   
                                FD.[PatientFName] ,   
                                FD.[Shelf] ,   
                                FD.[Box] ,
                                FD.[Position],
                                FD.[LocationOther],
                                FD.[Result],
                                FD.[SpecimenType],
                                PROD.[ProdDescription],
                                ST.[SpecimenDecode],
                                RT.[ResultDecode]     
                               FROM [DIS_PHLINVENTORY].[dbo].[FF_FreezerContents] AS FD
                                INNER JOIN ICDbS_Products AS PROD ON FD.FreezerID=PROD.ProductNoID
                                INNER JOIN FF_ddl_SpecimenType AS ST ON FD.SpecimenType=ST.SpecimenID
                                INNER JOIN FF_ddl_Results AS RT ON FD.Result=RT.ResultID
                                WHERE FD.[SpecimenType]=@SpecType AND FD.[Result]=@Result
                               ORDER BY Accession">

    <SelectParameters>         
<asp:QueryStringParameterName="SpecType"QueryStringField="SpecimenIn"/>   
<asp:QueryStringParameterName="Result"QueryStringField="ResultIn"/>
      </SelectParameters>               
</asp:SqlDataSource>

paging and sortin a gridview from a dataset

$
0
0

Hi all:

I know how to page and sort a gridview with data from sql server.

But how to page and sort with data from a dataset?

Thanks in advance

retrieve values from select query with single row output

$
0
0

My select query returns only single row. I've to assign the column values from this row to asp labels. How can I do it? I am usingdatatable for this. How to retrieve the values from the single row and assign to asp labels. Is this the correct way to do this. Please suggest. 

private void GetInflationRate (string goodsId, string RetailCode)
{
	WrapperClass wrc = new WrapperClass();
	wrc.SelectString = "select a.inflAmt as inflationAmt, b.InflId as inflationId, c.inflDis as inflationDiscout from goodsDetails a, retailDetails b,inflationDetails c " +						"where a.saleId  = '" + goodsId + "' and b.retailId = '" + RetailCode + "' and c.sale_Id= '" + goodsId + "' --";"

	DataTable dt = wrc.GetTable();
	DataRow row = dt.Rows[0];
	// how to retrieve the cell values and assign to asp lables
}

I've to assign the label 

lbl_inflationId = inflationId
lbl_inflationAmt = inflationAmt
lbl_inflationDisc = inflationDiscout

Can I use list for the same purpose? Please suggest me.

Thanks!

An error occurred during local report processing

$
0
0

Hi:

Dear all, I meet a big problem when using reportviewer 10.0;

the environment I set is IISEXPRESS. And then when I using following

codes:

    List<ReportParameter> param = new List<ReportParameter>();
    ..
    ReportViewer.LocalReport.SetParameters(param);

The system will show An error occurred during local report processing.  

The webconfig is following:


<compilation debug="true">
<assemblies>
<add assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</assemblies>
<buildProviders>
<add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</buildProviders>
</compilation>

<system.webServer><!--<add name="Reserved-ReportViewerWebControl-axd" path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> --></handlers></system.webServer>

I marked that because it will show duplicated declaring error message.

If there any way to solve that, thanks a lot.

Delete multiple rows at once via TableAdapter

$
0
0

Hello!

 I have a simple task, but I cannot get this task to work I have a TableAdapter. In that table adapter I've added a query like this:

DELETE FROM table WHERE id IN (@MyListOfID)

In code, I create a string with all my ids that I need to delete. Here is the code:

Dim StringOfIDs As New StringBuilder

For b = 0 To CheckEmployeesWithJobID.Rows.Count - 1
	StringOfIDs.Append(CheckEmployeesWithJobID(b).id)
	StringOfIDs.Append(",")
Next

' Delete not needed trainings
                Try
                    EmployeesTrainingsAdapter.DeleteTrainingWithIDs(StringOfIDs)
                Catch ex As Exception
                    LBL_ERR.ForeColor = Drawing.Color.Red
                    LBL_ERR.Text = "Failed to delete not needed trainings from employees with this job"
                    GC.Collect()
                    Exit Sub
                End Try

I receive an error because I provide a string , instead of an integer

Is there a way to do this via table adapter, or should I use the tableadapter individually for every row ?

Error when the ID is null

$
0
0
<asp:TemplateField HeaderText="Followup Person" 
                SortExpression="Followup Person">                                  <EditItemTemplate><asp:DropDownList ID="FollowupPersonDropDownList" runat="server" 
                         DataValueField="select_personnel_id" 
                         DataTextField="select_fup"                          
                         DataSourceID="SqlDataSource4" 
                         SelectedValue = '<%# Bind("Personnel_ID") %>'
                         AppendDataBoundItems="True">                          <asp:ListItem Text="Not Assigned" Value=null Selected=True />                        </asp:DropDownList><asp:SqlDataSource ID="SqlDataSource4" runat="server" 
                        ConnectionString="<%$ ConnectionStrings:RCS_2_02ConnectionString %>" 
                        SelectCommand="SELECT [UserId] AS select_personnel_id, ([UserName]) AS select_fup FROM aspnet_Users"></asp:SqlDataSource></EditItemTemplate></asp:TemplateField>

Error is thrown when the Bound Personnel_ID is null, how can I let the Selected value to be null and let the data source bound to this

drop down list as is?

Thanks

Jack

Drop in excel data

$
0
0

I am trying to create a form in which I can copy excel data and paste it into a table then interpret the data needed into a form that is manageable.  Basically I have tried a few different approaches to this, but all I want is to basically have a table which can have multiple lines of data pasted in. Then assign variables to the data and then order it in a table. What is the simplest way to get a drop in table?


ObjectDataSource doesn't trigger the Data Access Layer Method

$
0
0
<%@ Page Title="" Language="C#" MasterPageFile="~/RCS.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="RCS2_04.clerk.Default" %><asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"><script type="text/javascript">
        function OnSave(obj) {
            // Find the row this button is in
            var tr = $(obj).closest("tr");
            // Get the value from the edit control
            var firstNameEdit = tr.find("[id*='firstNameEdit']").val();
            // assign value to hidden input
            tr.find("[id*='firstNameHidden']").val(firstNameEdit);
            var lastNameEdit = tr.find("[id*='lastNameEdit']").val();
            tr.find("[id*='lastNameHidden']").val(lastNameEdit);
        }</script></asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="IconContentPlaceHolder" runat="server"></asp:Content><asp:Content ID="Content3" ContentPlaceHolderID="SideBarContentPlaceHolder" runat="server"></asp:Content><asp:Content ID="Content4" ContentPlaceHolderID="PageHeaderContentPlaceHolder" runat="server"></asp:Content><asp:Content ID="Content5" ContentPlaceHolderID="TableHeaderNamePlaceHolder" runat="server"></asp:Content><asp:Content ID="Content6" ContentPlaceHolderID="TableContentHolder" runat="server">          <div style='margin: 5px 5px 5px 5px; border: 1px solid blue; text-align: center;<%= Visibility("MSG") %>'>
        No record to display</div><div style='margin: 5px 5px 5px 5px; border: 1px; <%= Visibility("Navigation") %>'><table width="100%" border="0"><tr><td align="right">
                    Page Size&nbsp;:&nbsp;<asp:DropDownList ID="ddlPageSize" runat="server" AutoPostBack="true"><asp:ListItem Text="7" Selected="True" Value="7"></asp:ListItem><asp:ListItem Text="10" Value="10"></asp:ListItem><asp:ListItem Text="20" Value="20"></asp:ListItem><asp:ListItem Text="50" Value="50"></asp:ListItem><asp:ListItem Text="99" Value="99"></asp:ListItem><asp:ListItem Text="100" Value="100"></asp:ListItem><asp:ListItem Text="200" Value="200"></asp:ListItem></asp:DropDownList></td></tr><tr><td align="right"><asp:Label ID="lblCurrentPage" runat="server"></asp:Label></td></tr><tr><td align="right"><asp:LinkButton ID="lbtnFirst" runat="server" Text=" first " OnClick="lbtnFirst_Click"></asp:LinkButton>&nbsp; &nbsp;<asp:LinkButton ID="lbtnPrev" runat="server" Text=" previous " OnClick="lbtnPrev_Click"></asp:LinkButton>&nbsp;&nbsp;<asp:LinkButton ID="lbtnNext" runat="server" Text=" next " OnClick="lbtnNext_Click"></asp:LinkButton>&nbsp; &nbsp;<asp:LinkButton ID="lbtnLast" runat="server" Text=" last " OnClick="lbtnLast_Click"></asp:LinkButton></td></tr></table></div><asp:Repeater ID="rptIssues" runat="server" onitemcommand="rptIssues_ItemCommand" OnItemDataBound="OnItemDataBound">            <HeaderTemplate><table class="table table-hover table-bordered" width="100%" cellpadding="2" cellspacing="2"><tr><td></td><td style="width: 20%; font-weight: bold"><asp:LinkButton ID="lbtnItemNo" Text="Item #" runat="server" CommandName="ItemNo"></asp:LinkButton></td><td style="width: 20%; font-weight: bold"><asp:LinkButton ID="lbtnProjectCode" Text="Project Code" runat="server" CommandName="ProjectCode"></asp:LinkButton></td><td style="width: 20%; font-weight: bold"><asp:LinkButton ID="lbtnRespRaisedDate" Text="Response Raised Date" runat="server" CommandName="RespRaisedDate"></asp:LinkButton></td><td style="width: 20%; font-weight: bold"><asp:LinkButton ID="lbtnFirstName" Text="First Name" runat="server" CommandName="FName"></asp:LinkButton></td><td style="width: 20%; font-weight: bold"><asp:LinkButton ID="lbtnLastName" Text="Last Name" runat="server" CommandName="LName"></asp:LinkButton></td><td style="width: 20%; font-weight: bold"><asp:LinkButton ID="lbtnMobileNum" Text="Mobile Number" runat="server" CommandName="MobileNum"></asp:LinkButton></td><td style="width: 20%; font-weight: bold"><asp:LinkButton ID="lbtnEmail" Text="Email" runat="server" CommandName="Email"></asp:LinkButton>                            </td><td style="width: 20%; font-weight: bold"><asp:LinkButton ID="lbtnRespDesc" Text="Response Description" runat="server" CommandName="RespDesc"></asp:LinkButton></td><td style="width: 20%; font-weight: bold"><asp:LinkButton ID="lbtnSupportDoc" Text="Support Document" runat="server" CommandName="SupportDoc"></asp:LinkButton>                            </td></tr></HeaderTemplate><ItemTemplate>             <td><asp:ImageButton ID="ImageButton1" ImageUrl="../Images/EditDocument.png" runat="server" CommandName="edit" /><asp:ImageButton ID="ImageButton2" ImageUrl="../Images/Delete_black_32x32.png" runat="server"
                            CommandName="delete" /></td> <td><asp:Label runat="server" ID="itemNo"><%# Eval("ItemNo") %></asp:Label><asp:PlaceHolder runat="server" ID="itemNoPlaceHolder" /><input type="hidden" runat="server" id="itemNoHidden" visible="false" /></td><td><asp:Label runat="server" ID="projectCode"><%# Eval("ProjectCode") %></asp:Label><asp:PlaceHolder runat="server" ID="projectCodeEditPlaceHolder" /><input type="hidden" runat="server" id="projectCodeHidden" visible="false" /></td><td><asp:Label runat="server" ID="respRaisedDate"><%# Eval("RespRaisedDate",  "{0:dd-MMM-yyyy}") %></asp:Label><asp:PlaceHolder runat="server" ID="respRaisedDatePlaceHolder" /><input type="hidden" runat="server" id="respRaisedDateHidden" visible="false" /></td><td><asp:Label runat="server" ID="firstName"><%# Eval("FName") %></asp:Label><asp:PlaceHolder runat="server" ID="firstNameEditPlaceholder" /><input type="hidden" runat="server" id="firstNameHidden" visible="false" /></td><td><asp:Label runat="server" ID="lastName"><%# Eval("LName") %></asp:Label><asp:PlaceHolder runat="server" ID="lastNameEditPlaceholder" /><input type="hidden" runat="server" id="lastNameHidden" visible="false" /></td><td><asp:Label runat="server" ID="mobileNum"><%# Eval("MobileNum") %></asp:Label><asp:PlaceHolder runat="server" ID="mobileNumPlaceHolder" /><input type="hidden" runat="server" id="mobileNumHidden" visible="false" /></td><td><asp:Label runat="server" ID="email"><%# Eval("Email") %></asp:Label><asp:PlaceHolder runat="server" ID="emailPlaceHolder" /><input type="hidden" runat="server" id="emailHidden" visible="false" /></td><td><asp:Label runat="server" ID="respDesc"><%# Eval("RespDesc") %></asp:Label><asp:PlaceHolder runat="server" ID="respDescPlaceHolder" /><input type="hidden" runat="server" id="respDescHidden" visible="false" /></td><td><asp:Image runat="server" ID="supportDoc" ImageUrl = '<%# Eval("SupportDoc") %>' /></asp:Image><asp:PlaceHolder runat="server" ID="supportDocPlaceHolder" /><input type="hidden" runat="server" id="supportDocHidden" visible="false" /></td></tr>                 </ItemTemplate><FooterTemplate><tr><td><asp:ImageButton ID="Add" ImageUrl="../Images/112_Plus_Blue_32x32_72.png" runat="server"
                                OnClick="OnAddRecord" /></td><td><asp:TextBox runat="server" ID="NewItemNo" /></td><td><asp:TextBox runat="server" ID="NewProjectCode" /></td><td><asp:Calendar runat="server" ID="NewRespRaisedDate" /></td><td><asp:TextBox runat="server" ID="NewFirstName" /></td><td><asp:TextBox runat="server" ID="NewLastName" /></td><td><asp:TextBox runat="server" ID="NewMobileNum" /></td><td><asp:TextBox runat="server" ID="NewEmail" /></td><td><asp:TextBox runat="server" ID="NewRespDesc" /></td><td><asp:FileUpload runat="server" ID="NewSupportDoc" /></td></tr></table></FooterTemplate></asp:Repeater><asp:ObjectDataSource ID="MainIssueDS" runat="server" 
        InsertMethod="InsertIssue"
        SelectMethod="GetAllIssues"         
        TypeName="RCS2_04.common.IssueLogDataAccessLayer"          
        DataObjectTypeName="RCS2_04.common.Issue"><InsertParameters><asp:Parameter Name="ProjectCode" Type="Int32" /><asp:Parameter Name="RespRaisedDate" DbType="Date" /><asp:Parameter Name="FName" Type="String" /><asp:Parameter Name="LName" Type="String" /><asp:Parameter Name="MobileNum" Type="String" /><asp:Parameter Name="Email" Type="String" /><asp:Parameter Name="RespDesc" Type="String" /><asp:Parameter Name="SupportDoc" /></InsertParameters></asp:ObjectDataSource></asp:Content>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;


namespace RCS2_04.common
{ 
    public class IssueLogDataAccessLayer
    {
        public static List<Issue> GetAllIssues()
        {
            List<Issue> listIssues = new List<Issue>();

            string CS = ConfigurationManager.ConnectionStrings["RCS_2_02ConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(CS))
            {
                SqlCommand cmd = new SqlCommand(@"SELECT i.[ItemNo], i.[ProjectCode], i.[RespRaisedDate], i.[Lname], i.[Fname], i.[MobileNum], i.[Email], i.[RespDesc], s.[Image_Data] AS [SupportDoc]
                                                    FROM [IssueLog] AS i 
                                                    LEFT JOIN
                                                    [SupportDoc] AS s
                                                    ON i.ItemNo = s.ItemNo", con);

                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    Issue issue = new Issue();
                    issue.ItemNo = Convert.ToInt32(rdr["ItemNo"]);
                    issue.ProjectCode = Convert.ToInt32(rdr["ProjectCode"]);
                    issue.RespRaisedDate = Convert.ToDateTime(rdr["RespRaisedDate"]);
                    issue.FName = rdr["FName"].ToString();
                    issue.LName = rdr["FName"].ToString();
                    issue.MobileNum = rdr["MobileNum"].ToString();
                    issue.Email = rdr["Email"].ToString();
                    issue.RespDesc = rdr["RespDesc"].ToString();

                    listIssues.Add(issue);
                }

                return listIssues;

            }
        }

        public static void InsertIssue(Issue newIssue)
        { 
            string CS = ConfigurationManager.ConnectionStrings["RCS_2_02ConnectionString"].ConnectionString; 
            using (SqlConnection con = new SqlConnection(CS))
            {
                SqlTransaction trans = null;
                try
                {
                    trans = con.BeginTransaction("Insert_IssueLog_Coherent");

                    SqlCommand cmd = new SqlCommand(
                        @"INSERT INTO [IssueLog] ([ProjectCode], [RespRaisedDate], [Lname], [Fname],
                                [MobileNum], [Email], [RespDesc])
                              VALUES (@ProjectCode, @RespRaisedDate, @Lname, @Fname,
                                @MobileNum, @Email, @RespDesc", con);

                    cmd.Parameters.AddWithValue("@ProjectCode", newIssue.ProjectCode);
                    cmd.Parameters.AddWithValue("@RespRaisedDate", newIssue.RespRaisedDate);
                    cmd.Parameters.AddWithValue("@Fname", newIssue.FName);
                    cmd.Parameters.AddWithValue("@Lname", newIssue.LName);
                    cmd.Parameters.AddWithValue("@MobileNum", newIssue.MobileNum);
                    cmd.Parameters.AddWithValue("@Email", newIssue.Email);
                    cmd.Parameters.AddWithValue("@RespDesc", newIssue.RespDesc);

                    cmd.ExecuteNonQuery();

                    cmd = new SqlCommand(
                        @"INSERT INTO [SupportDoc] (ItemNo, Image_Data)
                              VALUES (@ItemNo, @Image_Data)", con);

                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("@ItemNo", newIssue.ItemNo);
                    cmd.Parameters.AddWithValue("@Image_Data", newIssue.SupportDoc);

                    cmd.ExecuteNonQuery();


                    trans.Commit();
                }
                catch (Exception e)
                {
                    trans.Rollback();
                }
            } // end using
        }
                
                
    }

    
}

I am trying to add a new record to the database, but when I place a breakpoint at the insertIssue method,

I pressed on the imagebutton with ID="Add", and Data Access Layer method of InsertIssue is not called.

How come?

Thanks

Jack

OnInserted not fired from sqldatasource

$
0
0

Really Strange, the breakpoint in the oninserted method is not caught and no emails were sent

Strange thing is that the master record of issue has actually been created, and the support document as well

Update:

Just wondering how to trigger the oninserted command with a custom insert image button?

<asp:SqlDataSource ID="SqlDataSource4" runat="server" 
        ConnectionString="<%$ ConnectionStrings:RCS_2_02ConnectionString %>" 
        DeleteCommand="DELETE FROM [IssueLog] WHERE [ItemNo] = @ItemNo"         
        InsertCommand="INSERT INTO [IssueLog] ([ProjectCode], [RespRaisedDate], [Lname], [Fname], [MobileNum], 
[Email], [RespDesc]) VALUES (@ProjectCode, @RespRaisedDate, @Lname, @Fname, @MobileNum, @Email,
@RespDesc);
INSERT INTO SupportDoc(ItemNo, Image_Data) VALUES (@ItemNo, @SupportDoc);
SET @NewItemNo = Scope_Identity()"
SelectCommand="SELECT i.[ItemNo], i.[ProjectCode], i.[RespRaisedDate], i.[Lname], i.[Fname],
i.[MobileNum], i.[Email], i.[RespDesc] , s.[Image_Data] AS [SupportDoc] FROM [IssueLog] AS i LEFT JOIN [SupportDoc] AS s ON i.ItemNo = s.ItemNo" UpdateCommand="UPDATE [IssueLog] SET [ProjectCode] = @ProjectCode, [RespRaisedDate] = @RespRaisedDate, [Lname] = @Lname, [Fname] = @Fname, [MobileNum] = @MobileNum, [Email] = @Email, [RespDesc] = @RespDesc WHERE [ItemNo] = @ItemNo; UPDATE SupportDoc SET Image_Data = @SupportDoc WHERE ItemNo = @ItemNo" oninserted="SqlDataSource4_Inserted"><DeleteParameters><asp:Parameter Name="ItemNo" /></DeleteParameters><InsertParameters><asp:Parameter Name="ProjectCode" /><asp:Parameter Name="RespRaisedDate" /><asp:Parameter Name="Lname" /><asp:Parameter Name="Fname" /><asp:Parameter Name="MobileNum" /><asp:Parameter Name="Email" /><asp:Parameter Name="RespDesc" /><asp:Parameter Name="ItemNo" /><asp:Parameter Name="SupportDoc" /><asp:Parameter Name="NewItemNo" Direction="Output" Type="Int32" /></InsertParameters><UpdateParameters><asp:Parameter Name="ProjectCode" /><asp:Parameter Name="RespRaisedDate" /><asp:Parameter Name="Lname" /><asp:Parameter Name="Fname" /><asp:Parameter Name="MobileNum" /><asp:Parameter Name="Email" /><asp:Parameter Name="RespDesc" /><asp:Parameter Name="ItemNo" /><asp:Parameter Name="SupportDoc" /></UpdateParameters></asp:SqlDataSource>
protected void SqlDataSource4_Inserted(object sender, SqlDataSourceStatusEventArgs e)
        {
            try
            {
                // Enter a approval record, awaiting for supervisor to assign                               

                // get the generated item no                 
                Int32 ItemNo = (Int32)e.Command.Parameters["@NewItemNo"].Value;

                Approvals app = new Approvals();

                SqlConnection conn = new SqlConnection();
                conn.ConnectionString = ConfigurationManager.ConnectionStrings
                                      ["RCS_2_02ConnectionString"].ConnectionString;
                SqlCommand command = new SqlCommand("insert into Approvals (ItemNo, AppType, ApprovePersonID, Reason) VALUES (@ItemNo, @AppType, @ApprovePersonID, @Reason)", conn);
                command.Parameters.AddWithValue("@ItemNo", ItemNo);

                // Enter Issue Log Type
                command.Parameters.AddWithValue("@AppType", 1);
                command.Parameters.AddWithValue("@ApprovePersonID", Session["userId"]);
                command.Parameters.AddWithValue("@Reason", "N/A");



                conn.Open();
                command.ExecuteNonQuery();

                conn.Close();

                String ClerkEmail = "";
                String SupervisorEmail = "";

                Helpers.GetEmailAddresses(ref ClerkEmail, ref SupervisorEmail);

                // 2) Send an Email notification to the followup person
                Helpers.SendingMail(ClerkEmail, SupervisorEmail, "New Issue Log Created", "New Issue Log Created");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

Accessing ObjectDataSource programmatically

$
0
0

Hi,

Is there a way of accessing an underlying instance of a class specified in the Type attribute of an ObjectDataSource?

Thanks,

Leszek

Import Excel Specific Cell contents to SQL Server

$
0
0

Hi Everyone,

I have Build an asp.net with c# backend and SQL Server 2008 R2,

I want to copy the contents of particular cells in each sheet to my SQL database;

for exmaple:  

in my database table i have 6 columns : Title --> Zip  {A4-->A9} ok

how can i insert : content of B4 in First column,B5 in 2nd column (FirstName) .....

 OK, 

Thank you ;)

all data not show in report after 12 am come why i need to 7 am

$
0
0

Hi guys

I make sql query to select data every day by getdate function 

In sql server 2005 i write the following query 

ALTER proc [dbo].[JeddahSalesAll]
as
SELECT ROW_NUMBER() OVER (ORDER BY dbo.[Jeddah-Live$Sales Header].No_) AS [S.N], dbo.[Jeddah-Live$Sales Line].[Document No_] AS 'OrderNo', 
dbo.[Jeddah-Live$Sales Header].[Bill-to Name] AS 'CustomerNo', dbo.[Jeddah-Live$Sales Line].Area AS 'Shippment Type', dbo.[Jeddah-Live$Sales Line].Description AS 'Description', 
dbo.[Jeddah-Live$Sales Header].[Pump No_] AS 'PumpNo', CAST(ROUND(dbo.[Jeddah-Live$Sales Line].Quantity, 0, 1) AS int) AS 'Required Qunatity', 
CAST(ROUND(dbo.[Jeddah-Live$Sales Line].[Quantity Shipped], 0, 1) AS int) AS 'Shipped Quantity', CAST(ROUND(dbo.[Jeddah-Live$Sales Line].[Outstanding Quantity], 0, 
1) AS int) AS 'Outstanding Qunatity '
FROM dbo.[Jeddah-Live$Sales Header] INNER JOIN
dbo.[Jeddah-Live$Sales Line] ON dbo.[Jeddah-Live$Sales Header].No_ = dbo.[Jeddah-Live$Sales Line].[Document No_] AND 
dbo.[Jeddah-Live$Sales Header].[Sell-to Customer No_] = dbo.[Jeddah-Live$Sales Line].[Sell-to Customer No_] 
WHERE DATEDIFF(d,dbo.[Jeddah-Live$Sales Line].[Shipment Date],GETDATE()) = 0

query above work success no any problem

only problem the order start 8 pm in date(31/03/2015) and finish 7 am in date(01/04/2015)

at next day

what i do to show the orders done from 12 am to 7 am to show them
meaning i need to show orders from 8 pm to 7 am
the query get data until 12 clock and stop
How to modify query to accept day tomorrow until 7 clock

if you have solution or suggestion to solve problem help me if possible

Invalid attempt to call Read when reader is closed

$
0
0

Everytime I run the page , im getting : 

Invalid attempt to call Read when reader is closed , the strange thing is that the table is filled with the data , meaning that the everything worked OK , i was able to retrieve the data from one table and write it to another

but why am i getting this error ... , below is my code in C# 

protected void Page_Load(object sender, EventArgs e)
    {
        string ipaddress;
        ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (ipaddress == "" || ipaddress == null)
        ipaddress = Request.ServerVariables["REMOTE_ADDR"];

        string ora = ipaddress;
        sqlconnet.Open();


        cmd = new SqlCommand("SELECT tbl_IPs.userid, tbl_IPs.IP, users.FirstName, users.LastName, users.userid AS useridO FROM tbl_IPs INNER JOIN users ON tbl_IPs.userid = users.userid WHERE (tbl_IPs.IP = @ora)", sqlconnet);

        cmd.Parameters.AddWithValue("@ora", ora);

     
        readIP = cmd.ExecuteReader();


        while (readIP.Read())
        {

            useridlabel.Text = Convert.ToString(readIP[0]);         
            Session["naf"] = (int)readIP["userid"];
            Session["LoginTime"] = DateTime.Now.ToString("dd/MM/yyyy");
            Session["naf"] = (int)readIP["userid"];
            Session["FN"] = (string)readIP["FirstName"];
            Session["LastName"] = (string)readIP["LastName"];
            Label1.Text = Convert.ToString(Session["naf"]);
            Session["IsAuthenticated"] = true;
            SqlCommand insertinfoIP = new SqlCommand("INSERT INTO [tbl_userinfo] ([FirstName],[LastName], " +"[IP],[logintime],[userid]) " +"VALUES (@FirstName,@LastName,@IP,@logintime,@userid)", sqlconnet);


            insertinfoIP.Parameters.Add("@FirstName", SqlDbType.NVarChar).Value = Session["FN"];
            insertinfoIP.Parameters.Add("@LastName", SqlDbType.NVarChar).Value = Session["LastName"];
            insertinfoIP.Parameters.Add("@IP", SqlDbType.NVarChar).Value = ipaddress;
            insertinfoIP.Parameters.Add("@logintime", SqlDbType.DateTime).Value = System.DateTime.Now.ToString();
            insertinfoIP.Parameters.Add("@userid", SqlDbType.Int).Value = Session["naf"];



            readIP.Close();
            insertinfoIP.ExecuteNonQuery();
            sqlconnet.Close();
           
        }

 

SqlDataSource.SelectParameters with variable or session from MySqlDataReader return nothing

$
0
0

Sorry for my english !

When I click on button 

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

ReadMyData(ConfigurationManager.ConnectionStrings("myconnection").ConnectionString)

End Sub

After

Public Sub ReadMyData(myConnString As String)

Dim myVariable As String = ""

Dim myConnection As New MySqlConnection(myConnString)
Dim myCommand As New MySqlCommand("mystoreprocedure", myConnection)

myCommand.CommandType = CommandType.StoredProcedure
myCommand.Parameters.AddWithValue("@pMyparam", "9063")

myConnection.Open()
Dim myReader As MySqlDataReader
myReader = myCommand.ExecuteReader()
' Always call Read before accessing data.
While myReader.Read()


myVariable  = myReader.GetString(0)

End While

Session("mySession") = myVariable
Me.SqlDataSource.SelectParameters(0).DefaultValue = Session("mySession")
Me.SqlDataSource.DataBind()

myReader.Close()
myConnection.Close()

End Sub 

My SqlDataSource and my datalist is always get nothing, I check everthing my datareader return 1234 and  myVariable  = 123

if I put like 
Me.SqlDataSource.SelectParameters(0).DefaultValue = "1234" instead is work perfectly.

Please help me , thank you 


Use SqlDataSource control to insert date into database

$
0
0

Hello

I added an SqlDataSource to my page, I configured it using the wizard

I deleted the insert parameters

I try to send insert parameters by VB code

every thing is okay except sending and saving date field

I use this code to send the date

instituteSqlDataSource.InsertParameters.Add("establishingDate", Date.Parse(Calendar1.SelectedDate))

field data type in the database is (date)

at insert I get an erro

it says , Incorrect format

any ideas please?

thank you

using C# to transfer data between Oracle and SQL Server ?

$
0
0

I'm pretty new to C# and .NET so please don't be too harsh if my question seems too simple [*-)]

For more than 7 years we are transfering data between an Oracle production server and SQL Server with the help of flat files.  Those flat files are worked with, transformed, some information added and then finaly imported into SQL Server.  This is causing too much problems and errors and I would like to use a new method way to transfer the data.

Since there is not much relationships between tables, I have about 30 data transfers to make every morning.  My question is: is C# the best and fastest way to take those 30 tables fro Oracle, transform them and import then in SQL Server ?  Or is there some other way that would be better ? SQL Server, XML, ?  Also, is it better to run all 30 queries in the same C# program, or run 30 seperate C# processes concurrently ?

Thanks in advance.

Nc

 

LINQ: Dynamic SQL Query within a dataset

$
0
0

I have the following method that grabs a string, removes all spaces and add an OR for each word.

string[] allWords = txtSearch.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string sql = "SELECT Books.ISBN, Books.Title, Books.Tag, Books.Image, Books.photoType, Publishers.Name AS publisherName FROM Books INNER JOIN Publishers ON Books.codPublisher = Publishers.codPublisher WHERE ";
using (SqlCommand command = new SqlCommand())
{
for (int i = 0; i < allWords.Length; ++i)
        {
              if (i > 0)
              sql += "OR ";

              string paramName = "@param" + i.ToString();
              sql += string.Format("(Books.Title LIKE {0}) ", paramName);
              command.Parameters.AddWithValue(paramName, allWords[i] + "%");
         }
         command.CommandText = sql;
 }

When I wanted to query my database I would simply do

BooksTableAdapter tableAdapterBooks = new BooksTableAdapter();
dataSetLibrary.BooksDataTable dataTableBooks;
dataTableBooks = tableAdapterBooks.getDataByTitle(searchText);

Seems like I cannot run SQL Commands within a DataSet. I have been told to use LINQ, but I have no ideia how to achieve this.

Get Total Price from all selected/filtered records.

$
0
0

Hello

My GridView has PageSize = Enabled

My SqlDataSource has "onSelecting" event and also Parameters and ControlParameters Enabled. 

User filtering database and GridView displaying paged results. 

I want to display some spesific values from this filtered results. 

"We have 100 items and Total Price is 100.000USD - Filtered 90 items 90000USD - displaying only 50 records and 50.000USD"

I can display total records via DataView, also displaying paged records too.

But how can get filtered total records and price I dont know.

How can I get this filtered results and display it?

Thanks in advance.

SqlDataSource ControlParameter still fires in UpdatePanel

$
0
0

I have a GridView connected to a SqlDataSource, which has a ControlParameter (SelectedValue) connected to a DropDownList. All works fine.

Now I want to use an UpdatePanel so the GridView only updates after I select from the DropDownList and click a Button.

I've enclosed the GridView and the DropDownList in separate UpdatePanels, and set the triggers, etc.

So far it still appears to work OK from the front end, the GridView doesn't update until I click the button.

But... if I trace the SQL going to the database, I can see that the SQL code that populates the SqlDataSource is still running, even though the GridView isn't being refreshed. (the DropDownList has AutoPostBack set for other reasons internal to its own UpdatePanel, but that shouldn't affect anything outside it).

I tried putting the SqlDataSource inside or outside the UpdatePanel but it makes no difference.

Does a ControlParameter on a SqlDataSource ignore/override the UpdatePanel functionality? Ideally I don't want to hit the database if I don't need to.

I'd rather have a declarative solution in the aspx file than resort to code, if possible.

Edit: I should say that I have set UpdateMode="Conditional" for both UpdatePanels

Viewing all 956 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>