Search Results

Search found 145 results on 6 pages for 'sqldataadapter'.

Page 5/6 | < Previous Page | 1 2 3 4 5 6  | Next Page >

  • Database concurrency issue in .NET application

    - by MC.
    If userA deleted OrderA while userB is modifying OrderA, then userB saves OrderA then there is no order in the database to be updated. My problem is there is no error! The SqlDataAdapter.Update succeeds and returns a "1" indicating a record was modified when this is not true. Does anybody know how this is supposed to work, thanks.

    Read the article

  • Creating an AJAX Accordion Menu

    - by jaullo
    Introduction Ajax is a powerful addition to asp.net that provides new functionality in a simple and agile  way This post is dedicated to creating a menu with ajax accordion type. About the Control The basic idea of this control, is to provide a serie of panels and show and hide information inside these panels. The use is very simple, we have to set each panel inside accordion control and give to each panel a Header and of course, we have to set the content of each panel.  To use accordion control, u need the ajax control toolkit. know the basic propertyes of accordion control:  Before start developing an accordion control, we have to know the basic properties for this control Other accordion propertyes  FramesPerSecond - Number of frames per second used in the transition animations RequireOpenedPane - Prevent closing the currently opened pane when its header is clicked (which ensures one pane is always open). The default value is true. SuppressHeaderPostbacks - Prevent the client-side click handlers of elements inside a header from firing (this is especially useful when you want to include hyperlinks in your headers for accessibility) DataSource - The data source to use. DataBind() must be called. DataSourceID - The ID of the data source to use. DataMember - The member to bind to when using a DataSourceID  AJAX Accordion Control Extender DataSource  The Accordion Control extender of AJAX Control toolkit can also be used as DataBound control. You can bind the data retrieved from the database to the Accordion control. Accordion Control consists of properties such as DataSource and DataSourceID (we can se it above) that can be used to bind the data. HeaderTemplate can used to display the header or title for the pane generated by the Accordion control, a click on which will open or close the ContentTemplate generated by binding the data with Accordion extender. When DataSource is passed to the Accordion control, also use the DataBind method to bind the data. The Accordion control bound with data auto generates the expand/collapse panes along with their headers.  This code represents the basic steps to bind the Accordion to a Datasource Collapse Public Sub getCategories() Dim sqlConn As New SqlConnection(conString) sqlConn.Open() Dim sqlSelect As New SqlCommand("SELECT * FROM Categories", sqlConn) sqlSelect.CommandType = System.Data.CommandType.Text Dim sqlAdapter As New SqlDataAdapter(sqlSelect) Dim myDataset As New DataSet() sqlAdapter.Fill(myDataset) sqlConn.Close() Accordion1.DataSource = myDataset.Tables(0).DefaultView Accordion1.DataBind()End Sub Protected Sub Accordion1_ItemDataBound(sender As Object, _ e As AjaxControlToolkit.AccordionItemEventArgs) If e.ItemType = AjaxControlToolkit.AccordionItemType.Content Then Dim sqlConn As New SqlConnection(conString) sqlConn.Open() Dim sqlSelect As New SqlCommand("SELECT productName " & _ "FROM Products where categoryID = '" + _ DirectCast(e.AccordionItem.FindControl("txt_categoryID"),_ HiddenField).Value + "'", sqlConn) sqlSelect.CommandType = System.Data.CommandType.Text Dim sqlAdapter As New SqlDataAdapter(sqlSelect) Dim myDataset As New DataSet() sqlAdapter.Fill(myDataset) sqlConn.Close() Dim grd As New GridView() grd = DirectCast(e.AccordionItem.FindControl("GridView1"), GridView) grd.DataSource = myDataset grd.DataBind() End If End Sub In the above code, we made two things, first, we made a sql select to database to retrieve all data from categories table, this data will be used to set the header and columns of the accordion.  Collapse <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <ajaxToolkit:Accordion ID="Accordion1" runat="server" TransitionDuration="100" FramesPerSecond="200" FadeTransitions="true" RequireOpenedPane="false" OnItemDataBound="Accordion1_ItemDataBound" ContentCssClass="acc-content" HeaderCssClass="acc-header" HeaderSelectedCssClass="acc-selected"> <HeaderTemplate> <%#DataBinder.Eval(Container.DataItem,"categoryName") %> </HeaderTemplate> <ContentTemplate> <asp:HiddenField ID="txt_categoryID" runat="server" Value='<%#DataBinder.Eval(Container.DataItem,"categoryID") %>' /> <asp:GridView ID="GridView1" runat="server" RowStyle-BackColor="#ededed" RowStyle-HorizontalAlign="Left" AutoGenerateColumns="false" GridLines="None" CellPadding="2" CellSpacing="2" Width="300px"> <Columns> <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Product Name" HeaderStyle-BackColor="#d1d1d1" HeaderStyle-ForeColor="#777777"> <ItemTemplate> <%#DataBinder.Eval(Container.DataItem,"productName") %> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </ContentTemplate> </ajaxToolkit:Accordion>  Here, we use <%#DataBinder.Eval(Container.DataItem,"categoryName") %> to bind accordion header with categoryName, so we made on header for each element found on database.    Creating a basic accordion control As we know, to use any of the ajax components, there must be a registered ScriptManager on our site, which will be responsible for managing our controls. So the first thing we will do is create our script manager.     Collapse <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> Then we define our accordion  element and establish some basic properties:    Collapse <cc1:Accordion ID="AccordionCtrl" runat="server" SelectedIndex="0" HeaderCssClass="accordionHeader" ContentCssClass="accordionContent" AutoSize="None" FadeTransitions="true" TransitionDuration="250" FramesPerSecond="40" For our work we must declare PANES accordion inside it, these breads will be responsible for contain information, links or information that we want to show.  Collapse <Panes> <cc1:AccordionPane ID="AccordionPane0" runat="server"> <Header>Matenimiento</Header> <Content> <li><a href="mypagina.aspx">My página de prueba</a></li> </Content> </cc1:AccordionPane> To end this work, we have to close all panels and our accordion Collapse </Panes> </cc1:Accordion> Finally complete our example should look like:  Collapse <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <cc1:Accordion ID="AccordionCtrl" runat="server" SelectedIndex="0" HeaderCssClass="accordionHeader" ContentCssClass="accordionContent" AutoSize="None" FadeTransitions="true" TransitionDuration="250" FramesPerSecond="40"> <Panes> <cc1:AccordionPane ID="AccordionPane0" runat="server"> <Header>Matenimiento</Header> <Content> <li><a href="mypagina.aspx">My página de prueba</a></li> </Content> </cc1:AccordionPane> </Panes> </cc1:Accordion>

    Read the article

  • C# Bind DataTable to Existing DataGridView Column Definitions

    - by Timothy
    I've been struggling with a NullReferenceException and hope someone here will be able to point me in the right direction. I'm trying to create and populate a DataTable and then show the results in a DataGridView control. The basic code follows, and Execution stops with a NullReferenceException at the point where I invoke the new UpdateResults_Delegate. Oddly enough, I can trace entries.Rows.Count successfully before I return it from QueryEventEntries, so I can at least show 1) entries is not a null reference, and 2) the DataTable contains rows of data. I know I have to be doing something wrong, but I just don't know what. private void UpdateResults(DataTable entries) { dataGridView.DataSource = entries; } private void button_Click(object sender, EventArgs e) { PerformQuery(); } private void PerformQuery() { DateTime start = new DateTime(dateTimePicker1.Value.Year, dateTimePicker1.Value.Month, dateTimePicker1.Value.Day, 0, 0, 0); DateTime stop = new DateTime(dateTimePicker2.Value.Year, dateTimePicker2.Value.Month, dateTimePicker2.Value.Day, 0, 0, 0); DataTable entries = QueryEventEntries(start, stop); UpdateResults(entries); } private DataTable QueryEventEntries(DateTime start, DateTime stop) { DataTable entries = new DataTable(); entries.Columns.AddRange(new DataColumn[] { new DataColumn("event_type", typeof(Int32)), new DataColumn("event_time", typeof(DateTime)), new DataColumn("event_detail", typeof(String))}); using (SqlConnection conn = new SqlConnection(DSN)) { using (SqlDataAdapter adapter = new SqlDataAdapter( "SELECT event_type, event_time, event_detail FROM event_log " + "WHERE event_time >= @start AND event_time <= @stop", conn)) { adapter.SelectCommand.Parameters.AddRange(new Object[] { new SqlParameter("@start", start), new SqlParameter("@stop", stop)}); adapter.Fill(entries); } } return entries; } Update I'd like to summarize and provide some additional information I've learned from the discussion here and debugging efforts since I originally posted this question. I am refactoring old code that retrieved records from a database, collected those records as an array, and then later iterated through the array to populate a DataGridView row by row. Threading was originally implemented to compensate and keep the UI responsive during the unnecessary looping. I have since stripped out Thread/Invoke; everything now occurs on the same execution thread (thank you, Sam). I am attempting to replace the slow, unwieldy approach using a DataTable which I can fill with a DataAdapter, and assign to the DataGridView through it's DataSource property (above code updated). I've iterated through the entries DataTable's rows to verify the table contains the expected data before assigning it as the DataGridView's DataSource. foreach (DataRow row in entries.Rows) { System.Diagnostics.Trace.WriteLine( String.Format("{0} {1} {2}", row[0], row[1], row[2])); } One of the column of the DataGridView is a custom DataGridViewColumn to stylize the event_type value. I apologize I didn't mention this before in the original post but I wasn't aware it was important to my problem. I have converted this column temporarily to a standard DataGridViewTextBoxColumn control and am no longer experiencing the Exception. The fields in the DataTable are appended to the list of fields that have been pre-specified in Design view of the DataGridView. The records' values are being populated in these appended fields. When the run time attempts to render the cell a null value is provided (as the value that should be rendered is done so a couple columns over). In light of this, I am re-titling and re-tagging the question. I would still appreciate it if others who have experienced this can instruct me on how to go about binding the DataTable to the existing column definitions of the DataGridView.

    Read the article

  • update datagridview using ajax in my asp.net without refreshing the page.(Display real time data)

    - by kurt_jackson19
    I need to display a real time data from MS SQL 2005. I saw some blogs that recommend Ajax to solve my problem. Basically, right now I have my default.aspx page only just for a workaround I could able to display the data from my DB. But once I add data manually to my DB there's no updating made. Any suggestions guys to fix this problem? I need to update datagridview with out refreshing the page. Here's my code on Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { FillDataGridView(); } protected void up1_Load(object sender, EventArgs e) { FillDataGridView(); } protected void FillDataGridView() { DataSet objDs = new DataSet(); SqlConnection myConnection = new SqlConnection (ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString); SqlDataAdapter myCommand; string select = "SELECT * FROM Categories"; myCommand = new SqlDataAdapter(select, myConnection); myCommand.SelectCommand.CommandType = CommandType.Text; myConnection.Open(); myCommand.Fill(objDs); GridView1.DataSource = objDs; GridView1.DataBind(); } } Code on my Default.aspx <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Ajax Sample</title> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"> <Scripts> <asp:ScriptReference Path="JScript.js" /> </Scripts> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server" OnLoad="up1_Load"> <ContentTemplate> <asp:GridView ID="GridView1" runat="server" Height="136px" Width="325px"/> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="GridView1" /> </Triggers> </asp:UpdatePanel> </form> </body> </html> My problem now is how to call or use the ajax.js and how to write a code to call the FillDataGridView() in my Default.aspx.cs page. Thank you guys, hope anyone can help me on this problem.

    Read the article

  • [Flex 4 and .Net] Retrieving tables from SQL database

    - by mG
    Hi everyone, As the title says, I want to retrieve tables of data from a SQL database, using Flex 4 and .Net WebService. I'm new to both Flex and DotNet. Please tell me a proper way to do it. This is what I've done so far: Retrieving an array of string: (this works) .Net: [WebMethod] public String[] getTestArray() { String[] arStr = { "AAA", "BBB", "CCC", "DDD" }; return arStr; } Flex 4: <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"> <fx:Script> <![CDATA[ import mx.collections.ArrayCollection; import mx.controls.Alert; import mx.rpc.events.ResultEvent; [Bindable] private var ac:ArrayCollection = new ArrayCollection(); protected function btn_clickHandler(event:MouseEvent):void { ws.getTestArray(); } protected function ws_resultHandler(event:ResultEvent):void { ac = event.result as ArrayCollection; Alert.show(ac.toString()); } ]]> </fx:Script> <fx:Declarations> <s:WebService id="ws" wsdl="http://localhost:50582/Service1.asmx?WSDL" result="ws_resultHandler(event)"/> </fx:Declarations> <s:Button x="10" y="30" label="Button" id="btn" click="btn_clickHandler(event)"/> </s:Application> Retrieving a DataTable: (this does not work) DotNet: [WebMethod] public DataTable getUsers() { DataTable dt = new DataTable("Users"); SqlConnection conn = new SqlConnection("server = 192.168.1.50; database = MyDatabase; user id = sa; password = 1234; integrated security = false"); SqlDataAdapter da = new SqlDataAdapter("select vFName, vLName, vEmail from Users", conn); da.Fill(dt); return dt; } Flex 4: <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"> <fx:Script> <![CDATA[ import mx.collections.ArrayCollection; import mx.controls.Alert; import mx.rpc.events.ResultEvent; [Bindable] private var ac:ArrayCollection = new ArrayCollection(); protected function btn_clickHandler(event:MouseEvent):void { ws.getUsers(); } protected function ws_resultHandler(event:ResultEvent):void { ac = event.result as ArrayCollection; Alert.show(ac.toString()); } ]]> </fx:Script> <fx:Declarations> <s:WebService id="ws" wsdl="http://localhost:50582/Service1.asmx?WSDL" result="ws_resultHandler(event)"/> </fx:Declarations> <s:Button x="10" y="30" label="Button" id="btn" click="btn_clickHandler(event)"/> </s:Application>

    Read the article

  • Ado.net Fill method not throwing error on running a Stored Procedure that does not exist.

    - by Mike
    I am using a combination of the Enterprise library and the original Fill method of ADO. This is because I need to open and close the command connection myself as I am capture the event Info Message Here is my code so far // Set Up Command SqlDatabase db = new SqlDatabase(ConfigurationManager.ConnectionStrings[ConnectionName].ConnectionString); SqlCommand command = db.GetStoredProcCommand(StoredProcName) as SqlCommand; command.Connection = db.CreateConnection() as SqlConnection; // Set Up Events for Logging command.StatementCompleted += new StatementCompletedEventHandler(command_StatementCompleted); command.Connection.FireInfoMessageEventOnUserErrors = true; command.Connection.InfoMessage += new SqlInfoMessageEventHandler(Connection_InfoMessage); // Add Parameters foreach (Parameter parameter in Parameters) { db.AddInParameter(command, parameter.Name, (System.Data.DbType)Enum.Parse(typeof(System.Data.DbType), parameter.Type), parameter.Value); } // Use the Old Style fill to keep the connection Open througout the population // and manage the Statement Complete and InfoMessage events SqlDataAdapter da = new SqlDataAdapter(command); DataSet ds = new DataSet(); // Open Connection command.Connection.Open(); // Populate da.Fill(ds); // Dispose of the adapter if (da != null) { da.Dispose(); } // If you do not explicitly close the connection here, it will leak! if (command.Connection.State == ConnectionState.Open) { command.Connection.Close(); } ... Now if I pass into the variable StoredProcName = "ThisProcDoesNotExists" And run this peice of code. The CreateCommand nor da.Fill through an error message. Why is this. The only way I can tell it did not run was that it returns a dataset with 0 tables in it. But when investigating the error it is not appearant that the procedure does not exist. EDIT Upon further investigation command.Connection.FireInfoMessageEventOnUserErrors = true; is causeing the error to be surpressed into the InfoMessage Event From BOL When you set FireInfoMessageEventOnUserErrors to true, errors that were previously treated as exceptions are now handled as InfoMessage events. All events fire immediately and are handled by the event handler. If is FireInfoMessageEventOnUserErrors is set to false, then InfoMessage events are handled at the end of the procedure. What I want is each print statement from Sql to create a new log record. Setting this property to false combines it as one big string. So if I leave the property set to true, now the question is can I discern a print message from an Error ANOTHER EDIT So now I have the code so that the flag is set to true and checking the error number in the method void Connection_InfoMessage(object sender, SqlInfoMessageEventArgs e) { // These are not really errors unless the Number >0 // if Number = 0 that is a print message foreach (SqlError sql in e.Errors) { if (sql.Number == 0) { Logger.WriteInfo("Sql Message",sql.Message); } else { // Whatever this was it was an error throw new DataException(String.Format("Message={0},Line={1},Number={2},State{3}", sql.Message, sql.LineNumber, sql.Number, sql.State)); } } } The issue now that when I throw the error it does not bubble up to the statement that made the call or even the error handler that is above that. It just bombs out on that line The populate looks like // Populate try { da.Fill(ds); } catch (Exception e) { throw new Exception(e.Message, e); } Now even though I see the calling codes and methods still in the Call Stack, this exception does not seem to bubble up?

    Read the article

  • Data adapter not filling my dataset

    - by Doug Ancil
    I have the following code: Imports System.Data.SqlClient Public Class Main Protected WithEvents DataGridView1 As DataGridView Dim instForm2 As New Exceptions Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles startpayrollButton.Click Dim ssql As String = "select MAX(payrolldate) AS [payrolldate], " & _ "dateadd(dd, ((datediff(dd, '17530107', MAX(payrolldate))/7)*7)+7, '17530107') AS [Sunday]" & _ "from dbo.payroll" & _ " where payrollran = 'no'" Dim oCmd As System.Data.SqlClient.SqlCommand Dim oDr As System.Data.SqlClient.SqlDataReader oCmd = New System.Data.SqlClient.SqlCommand Try With oCmd .Connection = New System.Data.SqlClient.SqlConnection("Initial Catalog=mdr;Data Source=xxxxx;uid=xxxxx;password=xxxxx") .Connection.Open() .CommandType = CommandType.Text .CommandText = ssql oDr = .ExecuteReader() End With If oDr.Read Then payperiodstartdate = oDr.GetDateTime(1) payperiodenddate = payperiodstartdate.AddSeconds(604799) Dim ButtonDialogResult As DialogResult ButtonDialogResult = MessageBox.Show(" The Next Payroll Start Date is: " & payperiodstartdate.ToString() & System.Environment.NewLine & " Through End Date: " & payperiodenddate.ToString()) If ButtonDialogResult = Windows.Forms.DialogResult.OK Then exceptionsButton.Enabled = True startpayrollButton.Enabled = False End If End If oDr.Close() oCmd.Connection.Close() Catch ex As Exception MessageBox.Show(ex.Message) oCmd.Connection.Close() End Try End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exceptionsButton.Click Dim connection As System.Data.SqlClient.SqlConnection Dim adapter As System.Data.SqlClient.SqlDataAdapter = New System.Data.SqlClient.SqlDataAdapter Dim connectionString As String = "Initial Catalog=mdr;Data Source=xxxxx;uid=xxxxx;password=xxxxx" Dim ds As New DataSet Dim _sql As String = "SELECT [Exceptions].Employeenumber,[Exceptions].exceptiondate, [Exceptions].starttime, [exceptions].endtime, [Exceptions].code, datediff(minute, starttime, endtime) as duration INTO scratchpad3" & _ " FROM Employees INNER JOIN Exceptions ON [Exceptions].EmployeeNumber = [Exceptions].Employeenumber" & _ " where [Exceptions].exceptiondate between @payperiodstartdate and @payperiodenddate" & _ " GROUP BY [Exceptions].Employeenumber, [Exceptions].Exceptiondate, [Exceptions].starttime, [exceptions].endtime," & _ " [Exceptions].code, [Exceptions].exceptiondate" connection = New SqlConnection(connectionString) connection.Open() Dim _CMD As SqlCommand = New SqlCommand(_sql, connection) _CMD.Parameters.AddWithValue("@payperiodstartdate", payperiodstartdate) _CMD.Parameters.AddWithValue("@payperiodenddate", payperiodenddate) adapter.SelectCommand = _CMD Try adapter.Fill(ds) If ds Is Nothing OrElse ds.Tables.Count = 0 OrElse ds.Tables(0).Rows.Count = 0 Then 'it's empty MessageBox.Show("There was no data for this time period. Press Ok to continue", "No Data") connection.Close() Exceptions.saveButton.Enabled = False Exceptions.Hide() Else connection.Close() End If Catch ex As Exception MessageBox.Show(ex.ToString) connection.Close() End Try Exceptions.Show() End Sub Private Sub payrollButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles payrollButton.Click Payrollfinal.Show() End Sub End Class and when I run my program and press this button Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exceptionsButton.Click I have my date range within a time that I know that my dataset should produce a result, but when I put a line break in my code here: adapter.Fill(ds) and look at it in debug, I show a table value of 0. If I run the same query that I have to produce these results in sql analyser, I see 1 result. Can someone see why my query on my form produces a different result than the sql analyser does? Also here is my schema for my two tables: Exceptions employeenumber varchar no 50 yes no no SQL_Latin1_General_CP1_CI_AS exceptiondate datetime no 8 yes (n/a) (n/a) NULL starttime datetime no 8 yes (n/a) (n/a) NULL endtime datetime no 8 yes (n/a) (n/a) NULL duration varchar no 50 yes no no SQL_Latin1_General_CP1_CI_AS code varchar no 50 yes no no SQL_Latin1_General_CP1_CI_AS approvedby varchar no 50 yes no no SQL_Latin1_General_CP1_CI_AS approved varchar no 50 yes no no SQL_Latin1_General_CP1_CI_AS time timestamp no 8 yes (n/a) (n/a) NULL employees employeenumber varchar no 50 no no no SQL_Latin1_General_CP1_CI_AS name varchar no 50 no no no SQL_Latin1_General_CP1_CI_AS initials varchar no 50 no no no SQL_Latin1_General_CP1_CI_AS loginname1 varchar no 50 yes no no SQL_Latin1_General_CP1_CI_AS

    Read the article

  • Get XML from Server for Use on Windows Phone

    - by psheriff
    When working with mobile devices you always need to take into account bandwidth usage and power consumption. If you are constantly connecting to a server to retrieve data for an input screen, then you might think about moving some of that data down to the phone and cache the data on the phone. An example would be a static list of US State Codes that you are asking the user to select from. Since this is data that does not change very often, this is one set of data that would be great to cache on the phone. Since the Windows Phone does not have an embedded database, you can just use an XML string stored in Isolated Storage. Of course, then you need to figure out how to get data down to the phone. You can either ship it with the application, or connect and retrieve the data from your server one time and thereafter cache it and retrieve it from the cache. In this blog post you will see how to create a WCF service to retrieve data from a Product table in a database and send that data as XML to the phone and store it in Isolated Storage. You will then read that data from Isolated Storage using LINQ to XML and display it in a ListBox. Step 1: Create a Windows Phone Application The first step is to create a Windows Phone application called WP_GetXmlFromDataSet (or whatever you want to call it). On the MainPage.xaml add the following XAML within the “ContentPanel” grid: <StackPanel>  <Button Name="btnGetXml"          Content="Get XML"          Click="btnGetXml_Click" />  <Button Name="btnRead"          Content="Read XML"          IsEnabled="False"          Click="btnRead_Click" />  <ListBox Name="lstData"            Height="430"            ItemsSource="{Binding}"            DisplayMemberPath="ProductName" /></StackPanel> Now it is time to create the WCF Service Application that you will call to get the XML from a table in a SQL Server database. Step 2: Create a WCF Service Application Add a new project to your solution called WP_GetXmlFromDataSet.Services. Delete the IService1.* and Service1.* files and the App_Data folder, as you don’t generally need these items. Add a new WCF Service class called ProductService. In the IProductService class modify the void DoWork() method with the following code: [OperationContract]string GetProductXml(); Open the code behind in the ProductService.svc and create the GetProductXml() method. This method (shown below) will connect up to a database and retrieve data from a Product table. public string GetProductXml(){  string ret = string.Empty;  string sql = string.Empty;  SqlDataAdapter da;  DataSet ds = new DataSet();   sql = "SELECT ProductId, ProductName,";  sql += " IntroductionDate, Price";  sql += " FROM Product";   da = new SqlDataAdapter(sql,    ConfigurationManager.ConnectionStrings["Sandbox"].ConnectionString);   da.Fill(ds);   // Create Attribute based XML  foreach (DataColumn col in ds.Tables[0].Columns)  {    col.ColumnMapping = MappingType.Attribute;  }   ds.DataSetName = "Products";  ds.Tables[0].TableName = "Product";  ret = ds.GetXml();   return ret;} After retrieving the data from the Product table using a DataSet, you will want to set each column’s ColumnMapping property to Attribute. Using attribute based XML will make the data transferred across the wire a little smaller. You then set the DataSetName property to the top-level element name you want to assign to the XML. You then set the TableName property on the DataTable to the name you want each element to be in your XML. The last thing you need to do is to call the GetXml() method on the DataSet object which will return an XML string of the data in your DataSet object. This is the value that you will return from the service call. The XML that is returned from the above call looks like the following: <Products>  <Product ProductId="1"           ProductName="PDSA .NET Productivity Framework"           IntroductionDate="9/3/2010"           Price="5000" />  <Product ProductId="3"           ProductName="Haystack Code Generator for .NET"           IntroductionDate="7/1/2010"           Price="599.00" />  ...  ...  ... </Products> The GetProductXml() method uses a connection string from the Web.Config file, so add a <connectionStrings> element to the Web.Config file in your WCF Service application. Modify the settings shown below as needed for your server and database name. <connectionStrings>  <add name="Sandbox"        connectionString="Server=Localhost;Database=Sandbox;                         Integrated Security=Yes"/></connectionStrings> The Product Table You will need a Product table that you can read data from. I used the following structure for my product table. Add any data you want to this table after you create it in your database. CREATE TABLE Product(  ProductId int PRIMARY KEY IDENTITY(1,1) NOT NULL,  ProductName varchar(50) NOT NULL,  IntroductionDate datetime NULL,  Price money NULL) Step 3: Connect to WCF Service from Windows Phone Application Back in your Windows Phone application you will now need to add a Service Reference to the WCF Service application you just created. Right-mouse click on the Windows Phone Project and choose Add Service Reference… from the context menu. Click on the Discover button. In the Namespace text box enter “ProductServiceRefrence”, then click the OK button. If you entered everything correctly, Visual Studio will generate some code that allows you to connect to your Product service. On the MainPage.xaml designer window double click on the Get XML button to generate the Click event procedure for this button. In the Click event procedure make a call to a GetXmlFromServer() method. This method will also need a “Completed” event procedure to be written since all communication with a WCF Service from Windows Phone must be asynchronous.  Write these two methods as follows: private const string KEY_NAME = "ProductData"; private void GetXmlFromServer(){  ProductServiceClient client = new ProductServiceClient();   client.GetProductXmlCompleted += new     EventHandler<GetProductXmlCompletedEventArgs>      (client_GetProductXmlCompleted);   client.GetProductXmlAsync();  client.CloseAsync();} void client_GetProductXmlCompleted(object sender,                                   GetProductXmlCompletedEventArgs e){  // Store XML data in Isolated Storage  IsolatedStorageSettings.ApplicationSettings[KEY_NAME] = e.Result;   btnRead.IsEnabled = true;} As you can see, this is a fairly standard call to a WCF Service. In the Completed event you get the Result from the event argument, which is the XML, and store it into Isolated Storage using the IsolatedStorageSettings.ApplicationSettings class. Notice the constant that I added to specify the name of the key. You will use this constant later to read the data from Isolated Storage. Step 4: Create a Product Class Even though you stored XML data into Isolated Storage when you read that data out you will want to convert each element in the XML file into an actual Product object. This means that you need to create a Product class in your Windows Phone application. Add a Product class to your project that looks like the code below: public class Product{  public string ProductName{ get; set; }  public int ProductId{ get; set; }  public DateTime IntroductionDate{ get; set; }  public decimal Price{ get; set; }} Step 5: Read Settings from Isolated Storage Now that you have the XML data stored in Isolated Storage, it is time to use it. Go back to the MainPage.xaml design view and double click on the Read XML button to generate the Click event procedure. From the Click event procedure call a method named ReadProductXml().Create this method as shown below: private void ReadProductXml(){  XElement xElem = null;   if (IsolatedStorageSettings.ApplicationSettings.Contains(KEY_NAME))  {    xElem = XElement.Parse(     IsolatedStorageSettings.ApplicationSettings[KEY_NAME].ToString());     // Create a list of Product objects    var products =         from prod in xElem.Descendants("Product")        orderby prod.Attribute("ProductName").Value        select new Product        {          ProductId = Convert.ToInt32(prod.Attribute("ProductId").Value),          ProductName = prod.Attribute("ProductName").Value,          IntroductionDate =             Convert.ToDateTime(prod.Attribute("IntroductionDate").Value),          Price = Convert.ToDecimal(prod.Attribute("Price").Value)        };     lstData.DataContext = products;  }} The ReadProductXml() method checks to make sure that the key name that you saved your XML as exists in Isolated Storage prior to trying to open it. If the key name exists, then you retrieve the value as a string. Use the XElement’s Parse method to convert the XML string to a XElement object. LINQ to XML is used to iterate over each element in the XElement object and create a new Product object from each attribute in your XML file. The LINQ to XML code also orders the XML data by the ProductName. After the LINQ to XML code runs you end up with an IEnumerable collection of Product objects in the variable named “products”. You assign this collection of product data to the DataContext of the ListBox you created in XAML. The DisplayMemberPath property of the ListBox is set to “ProductName” so it will now display the product name for each row in your products collection. Summary In this article you learned how to retrieve an XML string from a table in a database, return that string across a WCF Service and store it into Isolated Storage on your Windows Phone. You then used LINQ to XML to create a collection of Product objects from the data stored and display that data in a Windows Phone list box. This same technique can be used in Silverlight or WPF applications too. NOTE: You can download the complete sample code at my website. http://www.pdsa.com/downloads. Choose Tips & Tricks, then "Get XML From Server for Use on Windows Phone" from the drop-down. Good Luck with your Coding,Paul Sheriff ** SPECIAL OFFER FOR MY BLOG READERS **Visit http://www.pdsa.com/Event/Blog for a free video on Silverlight entitled Silverlight XAML for the Complete Novice - Part 1.  

    Read the article

  • Does DataAdapter.Fill() close its connection when an Exception is thrown?

    - by motto
    Hi, I am using ADO.NET (.NET 1.1) in a legacy app. I know that DataAdapter.Fill() opens and closes connections if the connection hasn't been opened manually before it's given to the DataAdapter. My question: Does it also close the connection if the .Fill() causes an Exception? (due to SQL Server cannot be reached, or whatever). Does it leak a connection or does it have a built-in Finally-clause to make sure the connection is being closed. Code Example: Dim cmd As New SqlCommand Dim da As New SqlDataAdapter Dim ds As New DataSet cmd.Connection = New SqlConnection(strConnection) cmd.CommandText = strSQL da.SelectCommand = cmd da.Fill(ds)

    Read the article

  • Grid View Pagination.

    - by Wondering
    Dear All, I have a grid view and I want to implement Pagination functionality.This is working fine. protected DataSet FillDataSet() { string source = "Database=GridTest;Server=Localhost;Trusted_Connection=yes"; con = new SqlConnection(source); cmd = new SqlCommand("proc_mygrid", con); ds = new DataSet(); da = new SqlDataAdapter(cmd); da.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind(); return ds; } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { int newPagenumber = e.NewPageIndex; GridView1.PageIndex = newPagenumber; GridView1.DataSource = FillDataSet(); GridView1.DataBind(); } But the problem is for each pagination I have to call FillDataSet(); Is there any way to stop that.Any other coding approach? Thanks.

    Read the article

  • dataset tables row count 'zero'

    - by James123
    I am using dataadapter.Fill() into dataset. But dataset returning tables rows count zero (0). When I ran same sp in sql mgmt. It is returning two tables data. If attributeId = 1 Then spString = "USP_group_1" ElseIf attributeId = 2 Then spString = "USP_group_2" ElseIf attributeId = 3 Then spString = "USP_group_3" End If sqlcmd_q.CommandTimeout = 120 sqlcmd_q.Connection = sqlCnn sqlcmd_q.CommandText = spString sqlcmd_q.CommandType = CommandType.StoredProcedure sqlcmd_q.Parameters.AddWithValue("@client_id", clientId) Try sqlCnn.Open() Dim daGrid As New SqlDataAdapter(sqlcmd_q) daGrid.Fill(dsGrid) daGrid.Dispose() Return dsGrid I don't understand why this happening?

    Read the article

  • How to sort a gridview once a radio button is selected

    - by metashockwave
    I'm trying to sort records in the gridview right after a radio button is selected. My approach is with the dataview, but because the dataset variable doesn't survive a round trip to the server, I don't know how to make this happen. please help! Public Sub GetCustomers() db.RunProcedure("usp_customers_get_all") db.doSort(radList.SelectedValue) gvCustomers.DataSource = db.MyView End Sub Protected Sub radList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radList.SelectedIndexChanged If radList.SelectedValue = 0 Then db.doSort(0) gvCustomers.DataSource = db.MyView End If If radList.SelectedValue = 1 Then db.doSort(1) gvCustomers.DataSource = db.MyView End If End Sub Public Sub doSort(ByVal strIn As Integer) If strIn = 0 Then MyView.Sort = "lastname, firstname" Else MyView.Sort = "username" End If End Sub Public Sub RunProcedure(ByVal strName As String) Dim objConnection As New SqlConnection(mstrConnection) Dim mdbDataAdapter As New SqlDataAdapter(strName, objConnection) Try mdbDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure Me.mDataset.Clear() mdbDataAdapter.Fill(mDataset, "tblCustomers") MyView.Table = mDataset.Tables("tblCustomers") Catch ex As Exception Throw New Exception("stored procedure is " & strName.ToString & " error is " & ex.Message) End Try End Sub

    Read the article

  • Click edit button twice in gridview asp.net c# issue

    - by Supriyo Banerjee
    I have a gridview created on a page where I want to provide an edit button for the user to click in. However the issue is the grid view row becomes editable only while clicking the edit button second time. Not sure what is going wrong here, any help would be appreciated. One additional point is my grid view is displayed on the page only on a click of a button and is not there on page_load event hence. Posting the code snippets: //MY Aspx code <Columns> <asp:TemplateField HeaderText="Slice" SortExpression="name"> <ItemTemplate> <asp:Label ID="lblslice" Text='<%# Eval("slice") %>' runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label ID="lblslice" Text='<%# Eval("slice") %>' runat="server"></asp:Label> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Metric" SortExpression="Description"> <ItemTemplate> <asp:Label ID="lblmetric" Text='<%# Eval("metric")%>' runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label ID="lblmetric" Text='<%# Eval("metric")%>' runat="server"></asp:Label> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Original" SortExpression="Type"> <ItemTemplate> <asp:Label ID="lbloriginal" Text='<%# Eval("Original")%>' runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label ID="lbloriginal" Text='<%# Eval("Original")%>' runat="server"></asp:Label> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="WOW" SortExpression="Market"> <ItemTemplate> <asp:Label ID="lblwow" Text='<%# Eval("WOW")%>' runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label ID="lblwow" Text='<%# Eval("WOW")%>' runat="server"></asp:Label> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Change" SortExpression="Market" > <ItemTemplate> <asp:Label ID="lblChange" Text='<%# Eval("Change")%>' runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="TxtCustomerID" Text='<%# Eval("Change") %> ' runat="server"></asp:TextBox> </EditItemTemplate> </asp:TemplateField> <asp:CommandField HeaderText="Edit" ShowEditButton="True" /> </Columns> </asp:GridView> //My code behind: protected void Page_Load(object sender, EventArgs e) { } public void populagridview1(string slice,string fromdate,string todate,string year) { SqlCommand cmd; SqlDataAdapter da; DataSet ds; cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "usp_geteventchanges"; cmd.Connection = conn; conn.Open(); SqlParameter param1 = new SqlParameter("@slice", slice); cmd.Parameters.Add(param1); SqlParameter param2 = new SqlParameter("@fromdate", fromdate); cmd.Parameters.Add(param2); SqlParameter param3 = new SqlParameter("@todate", todate); cmd.Parameters.Add(param3); SqlParameter param4 = new SqlParameter("@year", year); cmd.Parameters.Add(param4); da = new SqlDataAdapter(cmd); ds = new DataSet(); da.Fill(ds, "Table"); GridView1.DataSource = ds; GridView1.DataBind(); conn.Close(); } protected void ImpactCalc(object sender, EventArgs e) { populagridview1(ddl_slice.SelectedValue, dt_to_integer(Picker1.Text), dt_to_integer(Picker2.Text), Txt_Year.Text); } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { gvEditIndex = e.NewEditIndex; Gridview1.DataBind(); } My page layout This edit screen appears after clicking edit twice.. the grid view gets displayed on hitting the Calculate impact button. The data is from a backend stored procedure which is fired on clicking the Calculate impact button

    Read the article

  • Error: A SQLParamenter wtih ParameterName @myparm is not contained by this SQLParameter Collection

    - by SidC
    Good Morning, I'm working on an ASP.NET 3.5 webforms application and have written the following code: Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click Dim connectionString As String = WebConfigurationManager.ConnectionStrings("Diel_inventoryConnectionString").ConnectionString Dim con As New SqlConnection(connectionString) Dim adapter1 As New SqlDataAdapter adapter1.SelectCommand = New SqlCommand adapter1.SelectCommand.CommandType = CommandType.StoredProcedure adapter1.SelectCommand.CommandText = "PartSproc" Dim parmNSN As New SqlParameter("@NSN", SqlDbType.NVarChar) Dim parmName As New SqlParameter("@PartName", SqlDbType.NVarChar) txtNSN.Text = adapter1.SelectCommand.Parameters("@NSN").Value txtSearch.Text = adapter1.SelectCommand.Parameters("@PartName").Value Dim dt As New DataTable() adapter1.Fill(dt) MySearch.DataSource = dt MySearch.DataBind() End Sub When I run the page, I receive the error A SQLParameter with @NSN is not contained by this SQLParameter Collection. I tried using apostrophes around the @NSN and @PartName but that does not work either and presents expression expected error. How might I rectify the above code so that it references the @NSN and @PartName parameters correctly? Thanks, Sid

    Read the article

  • Howt o get the t-sql statements being used to Update a DataSet

    - by Dennis
    I've a c# DataSet object with one table in it, and put some data in it and i've made some changes to that dataset (by code). Is there a way to get the actual t-sql queries this dataset will perform on the sql server when I update the dataset to the database with code that looks something like this: var dataAdapter = new SqlDataAdapter(cmdText, connection); var affected = dataAdapter.Update(updatedDataSet); I want to know what queries this dataset will fire to the database so I can log these changes to a logfile in my c# program.

    Read the article

  • Losing DateTimeOffset precision when using C#

    - by Darvis Lombardo
    I have a SQL Server table with a CreatedDate field of type DateTimeOffset(2). A sample value which is in the table is 2010-03-01 15:18:58.57 -05:00 As an example, from within C# I retrieve this value like so: var cmd = new SqlCommand("SELECT CreatedDate FROM Entities WHERE EntityID = 2", cn); var da = new SqlDataAdapter(cmd); DataTable dt =new DataTable(); da.Fill(dt); And I look at the value: MessageBox.Show(dt.Rows[0][0].ToString()); The result is 2010-03-01 15:18:58 -05:00, which is missing the .57 that is stored in the database. If I look at dt.Rows[0][0] in the Watch window, I also do not see the .57, so it appears it has been truncated. Can someone shed some light on this? I need to use the date to match up with other records in the database and the .57 is needed. Thanks! Darvis

    Read the article

  • Trying to get JQuery Autocomplete working on Asp.Net page.

    - by JasonMHirst
    Can someone shed some light on the problem please: I have the following: $(document).ready(function () { $("#txtFirstContact").autocomplete({url:'http://localhost:7970/Home/FindSurname' }); }); On my Asp.Net page. The http request is a function on an MVC Controller and that code is here: Function FindSurname(ByVal surname As String, ByVal count As Integer) Dim sqlConnection As New SqlClient.SqlConnection sqlConnection.ConnectionString = My.Settings.sqlConnection Dim sqlCommand As New SqlClient.SqlCommand sqlCommand.CommandText = "SELECT ConSName FROM tblContact WHERE ConSName LIKE '" & surname & "%'" sqlCommand.Connection = sqlConnection Dim ds As New DataSet Dim da As New SqlClient.SqlDataAdapter(sqlCommand) da.Fill(ds, "Contact") sqlConnection.Close() Dim contactsArray As New List(Of String) For Each dr As DataRow In ds.Tables("Contact").Rows contactsArray.Add(dr.Item("ConSName")) Next Return Json(contactsArray, JsonRequestBehavior.AllowGet) End Function As far as I'm aware, the Controller is returning JSON data, however I don't know if the Function Parameters are correct, or indeed if the format returned is interprettable by the AutoComplete plugin. If anyone can assist in the matter I'd really appreciate it.

    Read the article

  • What's wrong in this SELECT statement

    - by user522211
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim SQLData As New System.Data.SqlClient.SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True") Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT * FROM Table1 WHERE Seats ='" & TextBox1.Text & "'", SQLData) SQLData.Open() Using adapter As New SqlDataAdapter(cmdSelect) Using table As New Data.DataTable() adapter.Fill(table) TextBox1.Text = [String].Join(", ", table.AsEnumerable().[Select](Function(r) r.Field(Of Integer)("seat_select"))) End Using End Using SQLData.Close() End Sub This line will be highlighted with blue line: TextBox1.Text = [String].Join(", ", table.AsEnumerable().[Select](Function(r) r.Field(Of Integer)("seat_select")))

    Read the article

  • return statement from within using

    - by Bob
    using (IDbCommand command = new SqlCommand()) { IDbDataAdapter adapter = new SqlDataAdapter(); DataSet ds = new DataSet(); adapter.SelectCommand = command; command.Connection = _dataAccess.Connection; command.CommandType = CommandType.StoredProcedure; command.CommandText = "GetProcData"; command.Parameters.Add(new SqlParameter("@ProcID ", procId)); adapter.Fill(ds); return ds.Tables[0].AsEnumerable(); } This returns an IEnumerable DataRow The question is that since the return is within the using statement, will it property dispose of the IDBCommand? I know I can easily refactor this so I change the scope of the DataSet outside of the using, but it is more of a wonder than anything else.

    Read the article

  • how to get empty row in DropDownList

    - by Gali
    hi i have this citys in my database: city1 city2 city3 city4 i what to see this in my DropDownList: [empty] city1 city2 city3 city4 this is my bind code: SQL = "select distinct City from MyTbl order by City"; dsClass = new DataSet(); adp = new SqlDataAdapter(SQL, Conn); adp.Fill(dsClass, "MyTbl"); adp.Dispose(); DropDownList3.DataSource = dsClass.Tables[0]; DropDownList3.DataTextField = dsClass.Tables[0].Columns[0].ColumnName.ToString(); DropDownList3.DataValueField = dsClass.Tables[0].Columns[0].ColumnName.ToString(); DropDownList3.DataBind(); how to do it (asp.net C#) ? thanks in advance

    Read the article

  • DataSet.GetChanges - Save the updated record in a different table than the source one

    - by John Dev
    I'm doing operation on a dataset containing data from a sql table named Test_1 and then get the updated records using the DataSet.GetChanges(DataRowState.Modified) function. Then i try to save the dataset containing the updated records on a different table than the source one (the table is names Test and has the same structure as Test_1) using the following statement: sqlDataAdapter.Update(changesDataSet,"Test"); I'm getting the following error : Update unable to find TableMapping['Test'] or DataTable 'Test' I'm new to ado.net and don't even know if it"s something possible. Any advice is welcome. Just to provide a bit of context. ETL jobs are importing data in temp table with same structure as the original but with _jobid suffix. Right after a rule engine is doing validation before updating the original table.

    Read the article

  • Dataset.ReadXml() - Invalid character in the given encoding

    - by NLV
    Hello all I have saved a dataset in the sql database in an xml column using the following code. XmlDataDocument dd = new XmlDataDocument(dataset); and passing this xml document as sql parameter using param.value = new XmlNodeReader(dd); The XML is like <NewDataSet><SubContractChangeOrders><AGCol>1</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>006</Contract_x0020_Number><ContractID>30</ContractID><ChangeOrderID>211</ChangeOrderID><Amount>0.0000</Amount><Udf_CostReimbursableFlag>false</Udf_CostReimbursableFlag><Udf_CustomerCode /><Udf_SubChangeOrderStatus /></SubContractChangeOrders><SubContractChangeOrders><AGCol>2</AGCol><SCO_x0020_Number>002</SCO_x0020_Number><Contract_x0020_Number>006</Contract_x0020_Number><ContractID>30</ContractID><ChangeOrderID>212</ChangeOrderID><Amount>0.0000</Amount><Udf_CostReimbursableFlag>false</Udf_CostReimbursableFlag></SubContractChangeOrders><SubContractChangeOrders><AGCol>3</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>111</Contract_x0020_Number><ContractID>87</ContractID><ChangeOrderID>12</ChangeOrderID><Amount>300.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>4</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>222</Contract_x0020_Number><ContractID>80</ContractID><ChangeOrderID>6</ChangeOrderID><Amount>100.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>5</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>777</Contract_x0020_Number><ContractID>79</ContractID><ChangeOrderID>5</ChangeOrderID><Amount>200.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>6</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>786</Contract_x0020_Number><ContractID>77</ContractID><ChangeOrderID>3</ChangeOrderID><Amount>100.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>7</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>787</Contract_x0020_Number><ContractID>78</ContractID><ChangeOrderID>4</ChangeOrderID><Amount>500.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>8</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con 009</Contract_x0020_Number><ContractID>219</ContractID><ChangeOrderID>78</ChangeOrderID><Amount>9000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>9</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con 010</Contract_x0020_Number><ContractID>220</ContractID><ChangeOrderID>79</ChangeOrderID><Amount>13000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>10</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con 012</Contract_x0020_Number><ContractID>222</ContractID><ChangeOrderID>83</ChangeOrderID><Amount>2300.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>11</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con 020</Contract_x0020_Number><ContractID>226</ContractID><ChangeOrderID>86</ChangeOrderID><Amount>5400.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>12</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con 021</Contract_x0020_Number><ContractID>227</ContractID><ChangeOrderID>87</ChangeOrderID><Amount>2300.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>13</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con001</Contract_x0020_Number><ContractID>208</ContractID><ChangeOrderID>72</ChangeOrderID><Amount>3000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>14</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con002</Contract_x0020_Number><ContractID>209</ContractID><ChangeOrderID>73</ChangeOrderID><Amount>400.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>15</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con003</Contract_x0020_Number><ContractID>210</ContractID><ChangeOrderID>74</ChangeOrderID><Amount>6000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>16</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con004</Contract_x0020_Number><ContractID>211</ContractID><ChangeOrderID>75</ChangeOrderID><Amount>9000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>17</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con005</Contract_x0020_Number><ContractID>213</ContractID><ChangeOrderID>76</ChangeOrderID><Amount>17000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>18</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Cont001</Contract_x0020_Number><ContractID>228</ContractID><ChangeOrderID>89</ChangeOrderID><Amount>2000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>19</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>PUR001</Contract_x0020_Number><ContractID>229</ContractID><ChangeOrderID>88</ChangeOrderID><Amount>1000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>20</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>PUR002</Contract_x0020_Number><ContractID>230</ContractID><ChangeOrderID>90</ChangeOrderID><Amount>3000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>21</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>SC-002</Contract_x0020_Number><ContractID>2</ContractID><ChangeOrderID>7</ChangeOrderID><Amount>200.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>22</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>SC-004</Contract_x0020_Number><ContractID>7</ContractID><ChangeOrderID>65</ChangeOrderID><Amount>1000.0000</Amount></SubContractChangeOrders></NewDataSet> I'm trying to read it back as follows using (SqlConnection con = new SqlConnection("Server=#####;Initial Catalog=#####;User ID=####;Pwd=########")) { using (SqlCommand com = new SqlCommand("select * from dbo.tbl_#####", con)) { using (SqlDataAdapter ada = new SqlDataAdapter(com)) { ada.Fill(dt); MemoryStream ms = new MemoryStream(); object contractXML1 = dt.Rows[0]["SCOXML1"]; System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bf.Serialize(ms, contractXML1); ms.Seek(0, SeekOrigin.Begin); ds.ReadXml(ms); } } } I'm getting the following error Data at the root level is invalid. Line 1, position 6. Any ideas? NLV

    Read the article

  • validation in datagrid while insert update in asp.net

    - by abhi
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default7.aspx.cs" Inherits="Default7" % <%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" % Untitled Page   <telerik:GridTemplateColumn Visible="false"> <ItemTemplate> <asp:Label ID="lblEmpID" runat="server" Text='<%# bind("pid") %>'> </asp:Label> </ItemTemplate> </telerik:GridTemplateColumn> <telerik:GridBoundColumn UniqueName="Fname" HeaderText="Fname" DataField="Fname" CurrentFilterFunction="NotIsNull" SortExpression="Fname"> </telerik:GridBoundColumn> <telerik:GridBoundColumn UniqueName="Lname" HeaderText="Lname" DataField="Lname" CurrentFilterFunction="NotIsNull" SortExpression="Lname"> </telerik:GridBoundColumn> <telerik:GridBoundColumn UniqueName="Designation" HeaderText="Designation" DataField="Designation" CurrentFilterFunction="NotIsNull" SortExpression="Designation"> </telerik:GridBoundColumn> <telerik:GridEditCommandColumn> </telerik:GridEditCommandColumn> <telerik:GridButtonColumn CommandName="Delete" Text="Delete" UniqueName="column"> </telerik:GridButtonColumn> </Columns> <EditFormSettings> <FormTemplate> <table> <tr> <td>Fname*</td> <td> <asp:HiddenField ID="Fname" runat="server" Visible="false" /> <asp:TextBox ID="txtFname" runat="server" Text='<%#("Fname")%>'> </asp:TextBox> <asp:RequiredFieldValidator ID="EvalFname" ControlToValidate="txtFname" ErrorMessage="Enter Name" runat="server" ValidationGroup="Update"> *</asp:RequiredFieldValidator> </td> </tr> <tr> <td>Lname*</td> <td> <asp:HiddenField ID="HiddenField1" runat="server" Visible="false" /> <asp:TextBox ID="txtLname" runat="server" Text='<%#("Lname")%>'> </asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="txtLname" ErrorMessage="Enter Name" runat="server" ValidationGroup="Update"> *</asp:RequiredFieldValidator> </td> </tr> <tr> <td>Designation* </td> <td> <asp:HiddenField ID="HiddenField2" runat="server" Visible="false" /> <asp:TextBox ID="txtDesignation" runat="server" Text='<%#("Designation")%>'> </asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="txtDesignation" ErrorMessage="Enter Designation" runat="server" ValidationGroup="Update"> *</asp:RequiredFieldValidator> </td> </tr> </table> </FormTemplate> <EditColumn UpdateText="Update record" UniqueName="EditCommandColumn1" CancelText="Cancel edit"> </EditColumn> </EditFormSettings> </MasterTableView> </telerik:RadGrid> </form> this is my code i want to perform validation using the required validators but i think m missing smthin so pls help, here's my code behind using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using Telerik.Web.UI; public partial class Default7 : System.Web.UI.Page { string strQry; public SqlDataAdapter da; public DataSet ds; public SqlCommand cmd; public DataTable dt; string strCon = "Data Source=MINETDEVDATA; Initial Catalog=ML_SuppliersProd; User Id=sa; Password=@MinetApps7;"; public SqlConnection con; protected void Page_Load(object sender, EventArgs e) { } protected void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e) { dt = new DataTable(); con = new SqlConnection(strCon); da = new SqlDataAdapter(); try { strQry = "SELECT * FROM table2"; con.Open(); da.SelectCommand = new SqlCommand(strQry,con); da.Fill(dt); RadGrid1.DataSource = dt; } finally { con.Close(); } } protected void RadGrid1_DeleteCommand(object source, Telerik.Web.UI.GridCommandEventArgs e) { con = new SqlConnection(strCon); cmd = new SqlCommand(); GridDataItem item = (GridDataItem)e.Item; string pid = item.OwnerTableView.DataKeyValues[item.ItemIndex]["pid"].ToString(); con.Open(); string delete = "DELETE from table2 where pid='"+pid+"'"; cmd.CommandText = delete; cmd.Connection = con; cmd.ExecuteNonQuery(); con.Close(); } protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e) { GridEditableItem radgriditem = e.Item as GridEditableItem; string pid = radgriditem.OwnerTableView.DataKeyValues[radgriditem.ItemIndex]["pid"].ToString(); string firstname = (radgriditem["Fname"].Controls[0] as TextBox).Text; string lastname = (radgriditem["Lname"].Controls[0] as TextBox).Text; string designation = (radgriditem["Designation"].Controls[0] as TextBox).Text; con = new SqlConnection(strCon); cmd = new SqlCommand(); try { con.Open(); string update = "UPDATE table2 set Fname='" + firstname + "',Lname='" + lastname + "',Designation='" + designation + "' WHERE pid='" + pid + "'"; cmd.CommandText = update; cmd.Connection = con; cmd.ExecuteNonQuery(); con.Close(); } catch (Exception ex) { RadGrid1.Controls.Add(new LiteralControl("Unable to update Reason: " + ex.Message)); e.Canceled = true; } } protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e) { GridEditFormInsertItem insertitem = (GridEditFormInsertItem)e.Item; string firstname = (insertitem["Fname"].Controls[0] as TextBox).Text; string lastname = (insertitem["Lname"].Controls[0] as TextBox).Text; string designation = (insertitem["Designation"].Controls[0] as TextBox).Text; con = new SqlConnection(strCon); cmd = new SqlCommand(); try { con.Open(); String insertQuery = "INSERT into table1(Fname,Lname,Designation) Values ('" + firstname + "','" + lastname + "','" + designation + "')"; cmd.CommandText = insertQuery; cmd.Connection = con; cmd.ExecuteNonQuery(); con.Close(); } catch(Exception ex) { RadGrid1.Controls.Add(new LiteralControl("Unable to insert Reason:" + ex.Message)); e.Canceled = true; } } }

    Read the article

  • edit row in gridview

    - by user576998
    Hi.I would like to help me with my code. I have 2 gridviews. In the first gridview the user can choose with a checkbox every row he wants. These rows are transfered in the second gridview. All these my code does them well.Now, I want to edit the quantity column in second gridview to change the value but i don't know what i must write in edit box. Here is my code: using System; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Collections; public partial class ShowLand : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindPrimaryGrid(); BindSecondaryGrid(); } } private void BindPrimaryGrid() { string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString; string query = "select * from Land"; SqlConnection con = new SqlConnection(constr); SqlDataAdapter sda = new SqlDataAdapter(query, con); DataTable dt = new DataTable(); sda.Fill(dt); gridview2.DataSource = dt; gridview2.DataBind(); } private void GetData() { DataTable dt; if (ViewState["SelectedRecords1"] != null) dt = (DataTable)ViewState["SelectedRecords1"]; else dt = CreateDataTable(); CheckBox chkAll = (CheckBox)gridview2.HeaderRow .Cells[0].FindControl("chkAll"); for (int i = 0; i < gridview2.Rows.Count; i++) { if (chkAll.Checked) { dt = AddRow(gridview2.Rows[i], dt); } else { CheckBox chk = (CheckBox)gridview2.Rows[i] .Cells[0].FindControl("chk"); if (chk.Checked) { dt = AddRow(gridview2.Rows[i], dt); } else { dt = RemoveRow(gridview2.Rows[i], dt); } } } ViewState["SelectedRecords1"] = dt; } private void SetData() { CheckBox chkAll = (CheckBox)gridview2.HeaderRow.Cells[0].FindControl("chkAll"); chkAll.Checked = true; if (ViewState["SelectedRecords1"] != null) { DataTable dt = (DataTable)ViewState["SelectedRecords1"]; for (int i = 0; i < gridview2.Rows.Count; i++) { CheckBox chk = (CheckBox)gridview2.Rows[i].Cells[0].FindControl("chk"); if (chk != null) { DataRow[] dr = dt.Select("id = '" + gridview2.Rows[i].Cells[1].Text + "'"); chk.Checked = dr.Length > 0; if (!chk.Checked) { chkAll.Checked = false; } } } } } private DataTable CreateDataTable() { DataTable dt = new DataTable(); dt.Columns.Add("id"); dt.Columns.Add("name"); dt.Columns.Add("price"); dt.Columns.Add("quantity"); dt.Columns.Add("total"); dt.AcceptChanges(); return dt; } private DataTable AddRow(GridViewRow gvRow, DataTable dt) { DataRow[] dr = dt.Select("id = '" + gvRow.Cells[1].Text + "'"); if (dr.Length <= 0) { dt.Rows.Add(); dt.Rows[dt.Rows.Count - 1]["id"] = gvRow.Cells[1].Text; dt.Rows[dt.Rows.Count - 1]["name"] = gvRow.Cells[2].Text; dt.Rows[dt.Rows.Count - 1]["price"] = gvRow.Cells[3].Text; dt.Rows[dt.Rows.Count - 1]["quantity"] = gvRow.Cells[4].Text; dt.Rows[dt.Rows.Count - 1]["total"] = gvRow.Cells[5].Text; dt.AcceptChanges(); } return dt; } private DataTable RemoveRow(GridViewRow gvRow, DataTable dt) { DataRow[] dr = dt.Select("id = '" + gvRow.Cells[1].Text + "'"); if (dr.Length > 0) { dt.Rows.Remove(dr[0]); dt.AcceptChanges(); } return dt; } protected void CheckBox_CheckChanged(object sender, EventArgs e) { GetData(); SetData(); BindSecondaryGrid(); } private void BindSecondaryGrid() { DataTable dt = (DataTable)ViewState["SelectedRecords1"]; gridview3.DataSource = dt; gridview3.DataBind(); } } and the source code is <asp:GridView ID="gridview2" runat="server" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource5"> <Columns> <asp:TemplateField> <HeaderTemplate> <asp:CheckBox ID="chkAll" runat="server" onclick = "checkAll(this);" AutoPostBack = "true" OnCheckedChanged = "CheckBox_CheckChanged"/> </HeaderTemplate> <ItemTemplate> <asp:CheckBox ID="chk" runat="server" onclick = "Check_Click(this)" AutoPostBack = "true" OnCheckedChanged = "CheckBox_CheckChanged" /> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" /> <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" /> <asp:BoundField DataField="price" HeaderText="price" SortExpression="price" /> <asp:BoundField DataField="quantity" HeaderText="quantity" SortExpression="quantity" /> <asp:BoundField DataField="total" HeaderText="total" SortExpression="total" /> </Columns> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource5" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Land]"></asp:SqlDataSource> <br /> </div> <div> <asp:GridView ID="gridview3" runat="server" AutoGenerateColumns = "False" DataKeyNames="id" EmptyDataText = "No Records Selected" > <Columns> <asp:BoundField DataField = "id" HeaderText = "id" /> <asp:BoundField DataField = "name" HeaderText = "name" ReadOnly="True" /> <asp:BoundField DataField = "price" HeaderText = "price" DataFormatString="{0:c}" ReadOnly="True" /> <asp:TemplateField HeaderText="quantity"> <EditItemTemplate> <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("quantity")%>'</asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("quantity") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField = "total" HeaderText = "total" DataFormatString="{0:c}" ReadOnly="True" /> <asp:CommandField ShowEditButton="True" /> </Columns> </asp:GridView> <asp:Label ID="totalLabel" runat="server"></asp:Label> <br /> </div> </form> </body> </html>

    Read the article

  • Populating FullCalendar events from MVC

    - by jasonmhirst
    I've having difficulty in populating FullCalendar from MVC and would like a little assistance on the matter please. I have the following code for my controller: Function GetEvents(ByVal [start] As Double, ByVal [end] As Double) As JsonResult Dim sqlConnection As New SqlClient.SqlConnection sqlConnection.ConnectionString = My.Settings.sqlConnection Dim sqlCommand As New SqlClient.SqlCommand sqlCommand.CommandText = "SELECT tripID AS ID, tripName AS Title, DATEDIFF(s, '1970-01-01 00:00:00', dateStart) AS [Start], DATEDIFF(s, '1970-01-01 00:00:00', dateEnd) AS [End] FROM tblTrip WHERE userID=18 AND DateStart IS NOT NULL" sqlCommand.Connection = sqlConnection Dim ds As New DataSet Dim da As New SqlClient.SqlDataAdapter(sqlCommand) da.Fill(ds, "Meetings") sqlConnection.Close() Dim meetings = From c In ds.Tables("Meetings") Select {c.Item("ID"), c.Item("Title"), "False", c.Item("Start"), c.Item("End")} Return Json(meetings.ToArray(), JsonRequestBehavior.AllowGet) End Function This does indeed run correctly but the format that is returned is: [[25,"South America 2008","False",1203033600,1227657600],[48,"Levant 2009","False",1231804800,1233619200],[49,"South America 2009","False",1235433600,1237420800],[50,"Italy 2009","False",1241049600,1256083200],[189,"Levant 2010a","False",1265414400,1267574400],[195,"Levant 2010a","False",1262736000,1262736000],[208,"Levant 2010a","False",1264982400,1267574400],[209,"Levant 2010a","False",1264982400,1265587200],[210,"Levant 2010","False",1264982400,1266969600],[211,"Levant 2010 b","False",1267056000,1267574400],[213,"South America 2010a","False",1268438400,1269648000],[214,"Levant 2010 c","False",1266364800,1264118400],[215,"South America 2010a","False",1268611200,1269648000],[217,"South America 2010","False",1268611200,1269561600],[218,"South America 2010 b","False",1268956800,1269388800],[227,"levant 2010 b","False",1265846400,1266192000]] And this is totally different to what I've seen on the post from here: http://stackoverflow.com/questions/2445359/jquery-fullcalendar-json-date-issue (note the lack of tag information and curly braces) Can someone please explain to me what I may be doing wrong and why my output isn't correctly formatted. TIA

    Read the article

< Previous Page | 1 2 3 4 5 6  | Next Page >