i have a function which is called on form load
it should retrieve some data from a view and fill the dataset
but when it reaches the da.Fill(ds); line, all of the code below it (including itself) is awkwardly jumped
then form loads and my function becomes useless
below is the body of my function
SqlConnection conn = create_conn();
conn.Open();
SqlCommand cmd = new SqlCommand("View1", conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("keyfield", System.Data.SqlDbType.Char).Value = keyfieldval;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds); // <--- THIS IS THE LINE
Form1.field1 = ds.Tables[0].Rows[0]["field1"].ToString();
Form1.field2 = ds.Tables[0].Rows[0]["field2"].ToString();
conn.Close();
Related
I have a stored procedure with multiple joins, pulling all the data into a resultset I.e in dataset, now I want to write a linq query over it. How can I do that?
I am expecting:
IEnumerable<SomeType> result;
[where I need to know how the Properties of SomeType are defined.]
This is what I have tried but it does not look efficient.
SqlCommand cmd = new SqlCommand("Select top 10 * from trade");
cmd.Connection = con;
if (con.State != ConnectionState.Open)
{
con.Open();
}
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
var result = dt.AsEnumerable();
string valresukir = string.Empty;
var sortResult = result.OrderBy(x => Convert.ToInt32(x["trade_num"]) > 12);
string valuedata = string.Empty;
foreach (var i in sortResult)
{
valuedata += i["trade_num"].ToString();
}
to can write linq query on data table like
var data= from dataRow in dt.AsEnumerable()
where dataRow.Field<int>("trade_num") > 12
select dataRow
if trade_num is integer . Take it as a example and add your conditions accordingly.
Hope it will help you.
I am trying to Import Excel file through asp.net code. but I am getting ArgumentException when I am trying to create OleDbConnection
An OLE DB Provider was not specified in the ConnectionString. An
example would be, 'Provider=SQLOLEDB;'.
Here is the code
if (FileUpload1.HasFile)
{
string path = string.Concat((Server.MapPath("~/temp/"+FileUpload1.FileName)));
FileUpload1.PostedFile.SaveAs(path);
OleDbConnection oleCon = new OleDbConnection("Povider=Microsoft.Ace.OLEDB.12.0;Data Source="+path+";Extended Properties = Excel 12.0;");
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]",oleCon);
OleDbDataAdapter dtap = new OleDbDataAdapter(cmd);
oleCon.Open();
DbDataReader rdr = cmd.ExecuteReader();
string con_str = #"Data source = .;Initial Catalog=practiceDB;Integrated security=True";
SqlBulkCopy bulkInsert = new SqlBulkCopy(con_str);
bulkInsert.DestinationTableName="Excel";
bulkInsert.WriteToServer(rdr);
oleCon.Close();
Array.ForEach(Directory.GetFiles((Server.MapPath("~/temp/"))),File.Delete);
Response.Write("<script>alert('Inserted')</script>");
I have the following subroutine. It takes INPUT as argument 1 and sends multi-value data OUTPUT as argument 2.
SUBROUTINE MV_TO_DATASET_SELECT_SUBROUTINE(ARG_INPUT,ARG_OUTPUT)
x = ARG_INPUT
ARG_OUTPUT = "100":#VM:"101":#VM:"102":#VM:"103":#FM:"Nancy":#VM:"Andrew":#VM:"Janet":#VM:"Margaret":#FM:"01/06/1991":#VM:"06/07/1996":#VM:"11/08/1999":#VM:"12/10/2001"
RETURN
The Schema of above subroutine’s multi-value data is as below.
DataSet ds = new DataSet();
DataTable dt = new DataTable("Employee");
ds.Tables.Add(dt);
dt.Columns.Add("ID",typeof(Int32));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("HireDate", typeof(DateTime));
You can achevieve this task one of the following ways:
Use MV_To_DataTable() and DataTable_To_MV(). You can create schema of
subroutine by dragging and dropping Empty DataTable into Empty
DataSet Deginer.
By draagging and dropping Visual Studio Server Explorer’s U2
Subroutine into DataSet Designer. U2 Subrotine returns
resultset/dataset by executing API such as ST=SQLExecDirect(#HSTMT,
"SELECT F1 AS COL1,F2 AS COL2 ,F3 AS COL3 FROM #TMP SLIST 9 ORDER BY
1")
Use MV_To_DataTable() and DataTable_To_MV()
Create ASP.NET Web Application Project. Type ‘WebApplication_Subroutine’ in Project Name.
Add Reference to U2NETDK Assembly (U2.Data.Client)
Change header ‘Welcome to ASP.NET!’ to ‘Welcome to U2 Toolkit for .NET Demo on Business Logic Subroutine’s multi-value string data to .NET DataSet!’
Open ‘Default.aspx’ file and Go to Design Mode.
Do the following:
Drag and Drop Button Control. Name it ‘Load’
Drag and Drop Button Control. Name it ‘Update’
Drag and Drop GridView Control.
Right Click on Solution Explorer. Select Add ->New Item-DataSet. In the Name box, type ‘Employee.xsd’
Drag and Drop DataTable into Designer. Change the name to ‘Employee’ Table.
Create 3 new Columns (U2 subroutine Schema):
ID – DataType : INT
Name – DataType : STRING
HireDate - DataType : DATE
Open ‘Default.aspx’ file in Design Mode. Double Click ‘Load Button’. It will create Event handler Code behind.
Cut and paste the following code.
protected void Button1_Click(object sender, EventArgs e)
{
U2ConnectionStringBuilder l = new U2ConnectionStringBuilder();
l.Server = "127.0.0.1";
l.UserID = "user";
l.Password = "pass";
l.Database = "HS.SALES";
l.ServerType = "universe";
string lconnstr = l.ToString();
U2Connection c = new U2Connection();
c.ConnectionString = lconnstr;
c.Open();
U2Command command = c.CreateCommand();
command.CommandText = "CALL MV_TO_DATASET_SELECT_SUBROUTINE(?,?)";
command.CommandType = CommandType.StoredProcedure;
U2Parameter p1 = new U2Parameter();
p1.Direction = ParameterDirection.InputOutput;
p1.Value = "";
p1.ParameterName = "#arg_input";
command.Parameters.Add(p1);
U2Parameter p2 = new U2Parameter();
p2.Direction = ParameterDirection.InputOutput;
p2.Value = "";
p2.ParameterName = "#arg_output";
command.Parameters.Add(p2);
command.ExecuteNonQuery();
Employee.EmployeeDataTable dt = new Employee.EmployeeDataTable();
command.Parameters[1].MV_To_DataTable(dt);
Session["GridDataset"] = dt;
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
Run the application. Press ‘Load’ Button.
Open ‘Default.aspx’ file in Design Mode. Double click ‘Update Button’. It will create Event Handler in Code behind page.
Cut and Paste the following Code.
protected void Button2_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)Session["GridDataset"];
//To TEST, change first row
string s1 = (string)dt.Rows[0]["Name"];
dt.Rows[0]["Name"] = s1 + "NewValue";
// get the modified rows
DataTable dt_changed = dt.GetChanges();
//call DATASET_TO_MV_UPDATE_SUBROUTINE
U2ConnectionStringBuilder l = new U2ConnectionStringBuilder();
l.Server = "127.0.0.1";
l.UserID = "user";
l.Password = "pass";
l.Database = "HS.SALES";
l.ServerType = "universe";
string lconnstr = l.ToString();
U2Connection c = new U2Connection();
c.ConnectionString = lconnstr;
c.Open();
U2Command command = c.CreateCommand();
command.CommandText = "CALL DATASET_TO_MV_UPDATE_SUBROUTINE(?)";
command.CommandType = CommandType.StoredProcedure;
U2Parameter p1 = new U2Parameter();
p1.Value = "";
p1.Direction = ParameterDirection.InputOutput;
p1.ParameterName = "#arg_data";
command.Parameters.Add(p1);
command.Parameters[0].DataTable_To_MV(dt_changed);
// modified data going to subroutine
string lData = (string)command.Parameters[0].Value;
command.ExecuteNonQuery();
}
See the Modified Value in the Debugger when you click Update Button.
U2 Subrotine returns resultset/dataset
Create U2 Data Connection in Visual Studio Server Explorer. Expand Store Procedures Node.
Go to subroutine that returns resultset/dataset. Drag and Drop subroutine into DataSet Designer.
It shows INPUT argument and resultset/dataset columns.
I have the following code which lets me append a gridview and detailview as PDF file
But what I hope to achieve is not to download it but to attach it as email to send to the designated user. Is there any way I can modify the code so that I can send it as email and instead of download.
Dim strQuery As String = "SELECT * FROM [PointOrder] WHERE PointOrderId =" & Session("PointOrder")
Dim cmd As New SqlCommand(strQuery)
Dim dt As DataTable = GetData(cmd)
Dim DetailsView1 As New DetailsView()
DetailsView1.AllowPaging = False
DetailsView1.DataSource = dt
DetailsView1.DataBind()
Dim strQuery2 As String = "SELECT PointsOrderDetail.RedeemId, Redeem.RedeemName, Redeem.RedeemPoints, PointsOrderDetail.RedeemOrderQuantity, Redeem.RedeemPoints * PointsOrderDetail.RedeemOrderQuantity AS Total_Points FROM PointsOrderDetail INNER JOIN Redeem ON PointsOrderDetail.RedeemId = Redeem.RedeemId WHERE PointsOrderDetail.PointOrderId = " & Session("PointOrder")
Dim cmd2 As New SqlCommand(strQuery2)
Dim dt2 As DataTable = GetData(cmd2)
Dim GridView1 As New GridView()
GridView1.AllowPaging = False
GridView1.DataSource = dt2
GridView1.DataBind()
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=" & Session("ID") & "-" & Session("PointOrder") & "-RedeemConfirm.pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
DetailsView1.RenderControl(hw)
GridView1.RenderControl(hw)
Dim sr As New StringReader(sw.ToString())
Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
Dim htmlparser As New HTMLWorker(pdfDoc)
PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
pdfDoc.Open()
htmlparser.Parse(sr)
pdfDoc.Close()
Response.Write(pdfDoc)
Response.End()
Private Function GetData(ByVal cmd As SqlCommand) As DataTable
Dim dt As New DataTable()
Dim strConnString As [String] = System.Configuration.ConfigurationManager.ConnectionStrings("LegacySGConnectionString").ConnectionString()
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter()
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
Return dt
Catch ex As Exception
Throw ex
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Function
as below i have code to display data,
it works very fine, while data available..
but it shows same data, if query doeent return any rows, it shows last loaded data,
even if query returns other data eventhough it shows last loaded data..
please help me out...
ReportDocument rptdoc = new ReportDocument();
Ds2 = new DataSet();
Ds2 = ClsPos.GetRejectedByPosition(int.Parse(Request.QueryString.Get("ID")));
string ReportName = Server.MapPath("RejectedCandidate.rpt");
rptdoc.Load(ReportName);
// Position Name
ParameterFields Parameters = new ParameterFields();
ParameterField idget = new ParameterField();
idget.Name = "PositionName";
ParameterDiscreteValue values = new ParameterDiscreteValue();
values.Value = Request.QueryString.Get("PositionName");
idget.CurrentValues.Add(values);
Parameters.Add(idget);
CRViewer1.ParameterFieldInfo = Parameters;
rptdoc.SetDataSource(Ds2.Tables["GetValues"]);
CRViewer1.ReportSource = ReportName;
CRViewer1.DisplayGroupTree = false;
use rptDoc.Refresh(); after loading report. i.e.
rptdoc.Load(ReportName);
rptDoc.Refresh();