Search Results

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

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

  • How can i pull an image and data from a Database?

    - by user1851377
    I am trying to pull data from a Database using C#.net and use a Foreach loop to make it visible on a page. Every time i run the code i only get one item that shows up when i know that there is at least 7 items in the DB. i have placed the code below for the C#. SqlConnection oConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["HomeGrownEnergyConnectionString"].ToString()); string sqlEnergy = "Select * from Product p where p.ProductTypeId=3"; SqlCommand oCmd = new SqlCommand(sqlEnergy, oConnection); DataTable dtenergy = new DataTable(); SqlDataAdapter oDa = new SqlDataAdapter(oCmd); try { oConnection.Open(); ; oDa.Fill(dtenergy); } catch (Exception ex) { lblnodata.Text = ex.Message; return; } finally { oConnection.Close(); } DataTableReader results = dtenergy.CreateDataReader(); if (results.HasRows) { results.Read(); foreach(DataRow result in dtenergy.Rows) { byte[] imgProd = result["ThumnailLocation"] as byte[]; ID.Text = result["ProductID"].ToString(); Name.Text = result["Name"].ToString(); price.Text = FormatPriceColumn(result["Price"].ToString()); } } Here is the code for the asp.net. <div> <asp:Image ID="imgProd" CssClass="ProdImg" runat="server" /> <asp:Label runat="server" ID="ID" /> <asp:Label runat="server" ID="Name" /> <asp:Label runat="server" ID="price" /> <asp:TextBox ID="txtQty" MaxLength="3" runat="server" Width="30px" /> <asp:Button runat="server" ID="Addtocart" Text="Add To Cart" CommandName="AddToCart" ItemStyle-CssClass="btnCol" /> If someone could please help me that would be great thanks.

    Read the article

  • transaction handling in dataset based insert/update in c#

    - by user3703611
    I am trying to insert bulk records in a sql server database table using dataset. But i am unable to do transaction handling. Please help me to apply transaction handling in below code. I am using adapter.UpdateCommand.Transaction = trans; but this line give me an error of Object reference not set to an instance of an object. Code: string ConnectionString = "server=localhost\\sqlexpress;database=WindowsApp;Integrated Security=SSPI;"; SqlConnection conn = new SqlConnection(ConnectionString); conn.Open(); SqlTransaction trans = conn.BeginTransaction(IsolationLevel.Serializable); SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Test ORDER BY Id", conn); SqlCommandBuilder builder = new SqlCommandBuilder(adapter); adapter.UpdateCommand.Transaction = trans; // Create a dataset object DataSet ds = new DataSet("TestSet"); adapter.Fill(ds, "Test"); // Create a data table object and add a new row DataTable TestTable = ds.Tables["Test"]; for (int i=1;i<=50;i++) { DataRow row = TestTable.NewRow(); row["Id"] = i; TestTable .Rows.Add(row); } // Update data adapter adapter.Update(ds, "Test"); trans.Commit(); conn.Close();

    Read the article

  • SQL Server Connection Timeout C#

    - by Termin8tor
    First off I'd like to let everyone know I have searched my particular problem and can't seem to find what's causing my problem. I have an SQL Server 2008 instance running on a network machine and a client I have written connecting to it. To connect I have a small segment of code that establishes a connection to an sql server 2008 instance and returns a DataTable populated with the results of whatever query I run against the server, all pretty standard stuff really. Anyway the issue is, whenever I open my program and call this method, upon the first call to my method, regardless as to what I've set my Connection Timeout value as in the connection string, it takes about 15 seconds and then times out. Bizarrely though the second or third call I make to the method will work without a problem. I have opened up the ports for SQL Server on the server machine as outlined in this article: How to Open firewall ports for SQL Server and verified that it is correctly configured. Can anyone see a particular problem in my code? string _connectionString = "Server=" + @Properties.Settings.Default.sqlServer + "; Initial Catalog=" + @Properties.Settings.Default.sqlInitialCatalog + ";User Id=" + @Properties.Settings.Default.sqlUsername + ";Password=" + @Properties.Settings.Default.sqlPassword + "; Connection Timeout=1"; private DataTable ExecuteSqlStatement(string command) { using (SqlConnection conn = new SqlConnection(_connectionString)) { try { conn.Open(); using (SqlDataAdapter adaptor = new SqlDataAdapter(command, conn)) { DataTable table = new DataTable(); adaptor.Fill(table); return table; } } catch (SqlException e) { throw e; } } } The SqlException that is caught at my catch is : "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding." This occurs at the conn.Open(); line in the code snippet I have included. If anyone has any ideas that'd be great!

    Read the article

  • TextBox change is not saved to DataTable

    - by SeaDrive
    I'm having trouble with a simple table edit in a Winform application. I must have missed a step. I have a DataSet containing a DataTable connected to a database with a SqlDataAdapter. There is a SqlCommandBuilder on the SqlDataAdapter. On the form, there are TextBoxes which are bound to the DataTable. The binding was done in the Designer and it machine-produced statements like this: this.tbLast.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.belkData, "belk_mem.last", true)); When I fill the row in the DataTable, the values from the database appear in the textboxes, but when I change contents of the TextBox, the changes are apparently not being going to the DataTable. When I try to save change both of the following return null: DataTable dtChanges = dtMem.GetChanges(); DataSet dsChanges = belkData.GetChanges(); What did I forget? Edit - response to mrlucmorin: The save is under a button. Code is: BindingContext[belkData, "belk_mem"].EndCurrentEdit(); try { DataSet dsChanges = belkData.GetChanges(); if (dsChanges != null) { int nRows = sdaMem.Update(dsChanges); MessageBox.Show("Row(s) Updated: " + nRows.ToString()); belkData.AcceptChanges(); } else { MessageBox.Show("Nothing to save.", "No changes"); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } I've tried putting in these statements without any change in behavior: dtMem.AcceptChanges(); belkData.AcceptChanges();

    Read the article

  • Programming Practice

    - by deepti
    public DataTable UserUpdateTempSettings(int install_id, int install_map_id, string Setting_value,string LogFile) { SqlConnection oConnection = new SqlConnection(sConnectionString); DataSet oDataset = new DataSet(); DataTable oDatatable = new DataTable(); SqlDataAdapter MyDataAdapter = new SqlDataAdapter(); try { oConnection.Open(); cmd = new SqlCommand("SP_HOTDOC_PRINTTEMPLATE_PERMISSION", oConnection); cmd.Parameters.Add(new SqlParameter ("@INSTALL_ID", install_id)); cmd.Parameters.Add(new SqlParameter ("@INSTALL_MAP_ID", install_map_id)); cmd.Parameters.Add(new SqlParameter("@SETTING_VALUE", Setting_value)); if (LogFile != "") { cmd.Parameters.Add(new SqlParameter("@LOGFILE",LogFile)); } cmd.CommandType = CommandType.StoredProcedure; MyDataAdapter.SelectCommand = cmd; cmd.ExecuteNonQuery(); MyDataAdapter.Fill(oDataset); oDatatable = oDataset.Tables[0]; return oDatatable; } catch (Exception ex) { Utils.ShowError(ex.Message); return oDatatable; } finally { if ((oConnection.State != ConnectionState.Closed) || (oConnection.State != ConnectionState.Broken)) { oConnection.Close(); } oDataset = null; oDatatable = null; oConnection.Dispose(); oConnection = null; } } i have used execute non query.. normally its not used with data adapter... if iam not using its giving me error.. is it bad programming practice to use execute non query with data adapter

    Read the article

  • How to compare date from database using C#?

    - by user1490374
    I would like to compare the date selected from the database (every entry in EndDate) and compare them with today date. Is there any way to do this programmatically? Like extracting the dates and comparing them individually? I need this because I need to update the status for the table. string username; username = HttpContext.Current.User.Identity.Name; string date = DateTime.Now.ToString("MM/dd/yyyy"); txtDate.Text = date; SqlConnection conn1 = new SqlConnection("Data Source=mydatasource\\sqlexpress;" + "Initial Catalog = Suite2; Integrated Security =SSPI"); SqlDataAdapter adapter; string end; end = "SELECT EndDate FROM Table_Message WHERE username = '" + username + "'"; adapter = new SqlDataAdapter(end, conn1); conn1.Open(); DataSet ds = new DataSet(); adapter.Fill(ds); //Execute the sql command GridView2.DataSource = ds; GridView2.DataBind(); conn1.Close();

    Read the article

  • Why does the MSDN library constantly say "Information Not Found"?

    - by Zian Choy
    Environment: VS 2008 Pro SP1 MSDN Library for VS2008SP1 Sample Code: Dim userDataset = New DataSet Dim myDataAdapter = New SqlDataAdapter("SELECT UserName FROM tblwebUsers WHERE name = @person", connect) myDataAdapter.SelectCommand.Parameters.Add("@person", SqlDbType.NVarChar) When I put my cursor on the "d" in "Add" and press F1, I get an "Information Not Found" error from the MSDN Library. Does anyone have any suggestions for addressing the issue?

    Read the article

  • Bulk inserting best way to about it? + Helping me understand fully what I found so far

    - by chobo2
    Hi So I saw this post here and read it and it seems like bulk copy might be the way to go. http://stackoverflow.com/questions/682015/whats-the-best-way-to-bulk-database-inserts-from-c I still have some questions and want to know how things actually work. So I found 2 tutorials. http://www.codeproject.com/KB/cs/MultipleInsertsIn1dbTrip.aspx#_Toc196622241 http://www.codeproject.com/KB/linq/BulkOperations_LinqToSQL.aspx First way uses 2 ado.net 2.0 features. BulkInsert and BulkCopy. the second one uses linq to sql and OpenXML. This sort of appeals to me as I am using linq to sql already and prefer it over ado.net. However as one person pointed out in the posts what he just going around the issue at the cost of performance( nothing wrong with that in my opinion) First I will talk about the 2 ways in the first tutorial I am using VS2010 Express, .net 4.0, MVC 2.0, SQl Server 2005 Is ado.net 2.0 the most current version? Based on the technology I am using, is there some updates to what I am going to show that would improve it somehow? Is there any thing that these tutorial left out that I should know about? BulkInsert I am using this table for all the examples. CREATE TABLE [dbo].[TBL_TEST_TEST] ( ID INT IDENTITY(1,1) PRIMARY KEY, [NAME] [varchar](50) ) SP Code USE [Test] GO /****** Object: StoredProcedure [dbo].[sp_BatchInsert] Script Date: 05/19/2010 15:12:47 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[sp_BatchInsert] (@Name VARCHAR(50) ) AS BEGIN INSERT INTO TBL_TEST_TEST VALUES (@Name); END C# Code /// <summary> /// Another ado.net 2.0 way that uses a stored procedure to do a bulk insert. /// Seems slower then "BatchBulkCopy" way and it crashes when you try to insert 500,000 records in one go. /// http://www.codeproject.com/KB/cs/MultipleInsertsIn1dbTrip.aspx#_Toc196622241 /// </summary> private static void BatchInsert() { // Get the DataTable with Rows State as RowState.Added DataTable dtInsertRows = GetDataTable(); SqlConnection connection = new SqlConnection(connectionString); SqlCommand command = new SqlCommand("sp_BatchInsert", connection); command.CommandType = CommandType.StoredProcedure; command.UpdatedRowSource = UpdateRowSource.None; // Set the Parameter with appropriate Source Column Name command.Parameters.Add("@Name", SqlDbType.VarChar, 50, dtInsertRows.Columns[0].ColumnName); SqlDataAdapter adpt = new SqlDataAdapter(); adpt.InsertCommand = command; // Specify the number of records to be Inserted/Updated in one go. Default is 1. adpt.UpdateBatchSize = 1000; connection.Open(); int recordsInserted = adpt.Update(dtInsertRows); connection.Close(); } So first thing is the batch size. Why would you set a batch size to anything but the number of records you are sending? Like I am sending 500,000 records so I did a Batch size of 500,000. Next why does it crash when I do this? If I set it to 1000 for batch size it works just fine. System.Data.SqlClient.SqlException was unhandled Message="A transport-level error has occurred when sending the request to the server. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)" Source=".Net SqlClient Data Provider" ErrorCode=-2146232060 Class=20 LineNumber=0 Number=233 Server="" State=0 StackTrace: at System.Data.Common.DbDataAdapter.UpdatedRowStatusErrors(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount) at System.Data.Common.DbDataAdapter.UpdatedRowStatus(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount) at System.Data.Common.DbDataAdapter.Update(DataRow[] dataRows, DataTableMapping tableMapping) at System.Data.Common.DbDataAdapter.UpdateFromDataTable(DataTable dataTable, DataTableMapping tableMapping) at System.Data.Common.DbDataAdapter.Update(DataTable dataTable) at TestIQueryable.Program.BatchInsert() in C:\Users\a\Downloads\TestIQueryable\TestIQueryable\TestIQueryable\Program.cs:line 124 at TestIQueryable.Program.Main(String[] args) in C:\Users\a\Downloads\TestIQueryable\TestIQueryable\TestIQueryable\Program.cs:line 16 InnerException: Time it took to insert 500,000 records with insert batch size of 1000 took "2 mins and 54 seconds" Of course this is no official time I sat there with a stop watch( I am sure there are better ways but was too lazy to look what they where) So I find that kinda slow compared to all my other ones(expect the linq to sql insert one) and I am not really sure why. Next I looked at bulkcopy /// <summary> /// An ado.net 2.0 way to mass insert records. This seems to be the fastest. /// http://www.codeproject.com/KB/cs/MultipleInsertsIn1dbTrip.aspx#_Toc196622241 /// </summary> private static void BatchBulkCopy() { // Get the DataTable DataTable dtInsertRows = GetDataTable(); using (SqlBulkCopy sbc = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity)) { sbc.DestinationTableName = "TBL_TEST_TEST"; // Number of records to be processed in one go sbc.BatchSize = 500000; // Map the Source Column from DataTabel to the Destination Columns in SQL Server 2005 Person Table // sbc.ColumnMappings.Add("ID", "ID"); sbc.ColumnMappings.Add("NAME", "NAME"); // Number of records after which client has to be notified about its status sbc.NotifyAfter = dtInsertRows.Rows.Count; // Event that gets fired when NotifyAfter number of records are processed. sbc.SqlRowsCopied += new SqlRowsCopiedEventHandler(sbc_SqlRowsCopied); // Finally write to server sbc.WriteToServer(dtInsertRows); sbc.Close(); } } This one seemed to go really fast and did not even need a SP( can you use SP with bulk copy? If you can would it be better?) BatchCopy had no problem with a 500,000 batch size.So again why make it smaller then the number of records you want to send? I found that with BatchCopy and 500,000 batch size it took only 5 seconds to complete. I then tried with a batch size of 1,000 and it only took 8 seconds. So much faster then the bulkinsert one above. Now I tried the other tutorial. USE [Test] GO /****** Object: StoredProcedure [dbo].[spTEST_InsertXMLTEST_TEST] Script Date: 05/19/2010 15:39:03 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[spTEST_InsertXMLTEST_TEST](@UpdatedProdData nText) AS DECLARE @hDoc int exec sp_xml_preparedocument @hDoc OUTPUT,@UpdatedProdData INSERT INTO TBL_TEST_TEST(NAME) SELECT XMLProdTable.NAME FROM OPENXML(@hDoc, 'ArrayOfTBL_TEST_TEST/TBL_TEST_TEST', 2) WITH ( ID Int, NAME varchar(100) ) XMLProdTable EXEC sp_xml_removedocument @hDoc C# code. /// <summary> /// This is using linq to sql to make the table objects. /// It is then serailzed to to an xml document and sent to a stored proedure /// that then does a bulk insert(I think with OpenXML) /// http://www.codeproject.com/KB/linq/BulkOperations_LinqToSQL.aspx /// </summary> private static void LinqInsertXMLBatch() { using (TestDataContext db = new TestDataContext()) { TBL_TEST_TEST[] testRecords = new TBL_TEST_TEST[500000]; for (int count = 0; count < 500000; count++) { TBL_TEST_TEST testRecord = new TBL_TEST_TEST(); testRecord.NAME = "Name : " + count; testRecords[count] = testRecord; } StringBuilder sBuilder = new StringBuilder(); System.IO.StringWriter sWriter = new System.IO.StringWriter(sBuilder); XmlSerializer serializer = new XmlSerializer(typeof(TBL_TEST_TEST[])); serializer.Serialize(sWriter, testRecords); db.insertTestData(sBuilder.ToString()); } } So I like this because I get to use objects even though it is kinda redundant. I don't get how the SP works. Like I don't get the whole thing. I don't know if OPENXML has some batch insert under the hood but I do not even know how to take this example SP and change it to fit my tables since like I said I don't know what is going on. I also don't know what would happen if the object you have more tables in it. Like say I have a ProductName table what has a relationship to a Product table or something like that. In linq to sql you could get the product name object and make changes to the Product table in that same object. So I am not sure how to take that into account. I am not sure if I would have to do separate inserts or what. The time was pretty good for 500,000 records it took 52 seconds The last way of course was just using linq to do it all and it was pretty bad. /// <summary> /// This is using linq to sql to to insert lots of records. /// This way is slow as it uses no mass insert. /// Only tried to insert 50,000 records as I did not want to sit around till it did 500,000 records. /// http://www.codeproject.com/KB/linq/BulkOperations_LinqToSQL.aspx /// </summary> private static void LinqInsertAll() { using (TestDataContext db = new TestDataContext()) { db.CommandTimeout = 600; for (int count = 0; count < 50000; count++) { TBL_TEST_TEST testRecord = new TBL_TEST_TEST(); testRecord.NAME = "Name : " + count; db.TBL_TEST_TESTs.InsertOnSubmit(testRecord); } db.SubmitChanges(); } } I did only 50,000 records and that took over a minute to do. So I really narrowed it done to the linq to sql bulk insert way or bulk copy. I am just not sure how to do it when you have relationship for either way. I am not sure how they both stand up when doing updates instead of inserts as I have not gotten around to try it yet. I don't think I will ever need to insert/update more than 50,000 records at one type but at the same time I know I will have to do validation on records before inserting so that will slow it down and that sort of makes linq to sql nicer as your got objects especially if your first parsing data from a xml file before you insert into the database. Full C# code using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using System.Data; using System.Data.SqlClient; namespace TestIQueryable { class Program { private static string connectionString = ""; static void Main(string[] args) { BatchInsert(); Console.WriteLine("done"); } /// <summary> /// This is using linq to sql to to insert lots of records. /// This way is slow as it uses no mass insert. /// Only tried to insert 50,000 records as I did not want to sit around till it did 500,000 records. /// http://www.codeproject.com/KB/linq/BulkOperations_LinqToSQL.aspx /// </summary> private static void LinqInsertAll() { using (TestDataContext db = new TestDataContext()) { db.CommandTimeout = 600; for (int count = 0; count < 50000; count++) { TBL_TEST_TEST testRecord = new TBL_TEST_TEST(); testRecord.NAME = "Name : " + count; db.TBL_TEST_TESTs.InsertOnSubmit(testRecord); } db.SubmitChanges(); } } /// <summary> /// This is using linq to sql to make the table objects. /// It is then serailzed to to an xml document and sent to a stored proedure /// that then does a bulk insert(I think with OpenXML) /// http://www.codeproject.com/KB/linq/BulkOperations_LinqToSQL.aspx /// </summary> private static void LinqInsertXMLBatch() { using (TestDataContext db = new TestDataContext()) { TBL_TEST_TEST[] testRecords = new TBL_TEST_TEST[500000]; for (int count = 0; count < 500000; count++) { TBL_TEST_TEST testRecord = new TBL_TEST_TEST(); testRecord.NAME = "Name : " + count; testRecords[count] = testRecord; } StringBuilder sBuilder = new StringBuilder(); System.IO.StringWriter sWriter = new System.IO.StringWriter(sBuilder); XmlSerializer serializer = new XmlSerializer(typeof(TBL_TEST_TEST[])); serializer.Serialize(sWriter, testRecords); db.insertTestData(sBuilder.ToString()); } } /// <summary> /// An ado.net 2.0 way to mass insert records. This seems to be the fastest. /// http://www.codeproject.com/KB/cs/MultipleInsertsIn1dbTrip.aspx#_Toc196622241 /// </summary> private static void BatchBulkCopy() { // Get the DataTable DataTable dtInsertRows = GetDataTable(); using (SqlBulkCopy sbc = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity)) { sbc.DestinationTableName = "TBL_TEST_TEST"; // Number of records to be processed in one go sbc.BatchSize = 500000; // Map the Source Column from DataTabel to the Destination Columns in SQL Server 2005 Person Table // sbc.ColumnMappings.Add("ID", "ID"); sbc.ColumnMappings.Add("NAME", "NAME"); // Number of records after which client has to be notified about its status sbc.NotifyAfter = dtInsertRows.Rows.Count; // Event that gets fired when NotifyAfter number of records are processed. sbc.SqlRowsCopied += new SqlRowsCopiedEventHandler(sbc_SqlRowsCopied); // Finally write to server sbc.WriteToServer(dtInsertRows); sbc.Close(); } } /// <summary> /// Another ado.net 2.0 way that uses a stored procedure to do a bulk insert. /// Seems slower then "BatchBulkCopy" way and it crashes when you try to insert 500,000 records in one go. /// http://www.codeproject.com/KB/cs/MultipleInsertsIn1dbTrip.aspx#_Toc196622241 /// </summary> private static void BatchInsert() { // Get the DataTable with Rows State as RowState.Added DataTable dtInsertRows = GetDataTable(); SqlConnection connection = new SqlConnection(connectionString); SqlCommand command = new SqlCommand("sp_BatchInsert", connection); command.CommandType = CommandType.StoredProcedure; command.UpdatedRowSource = UpdateRowSource.None; // Set the Parameter with appropriate Source Column Name command.Parameters.Add("@Name", SqlDbType.VarChar, 50, dtInsertRows.Columns[0].ColumnName); SqlDataAdapter adpt = new SqlDataAdapter(); adpt.InsertCommand = command; // Specify the number of records to be Inserted/Updated in one go. Default is 1. adpt.UpdateBatchSize = 500000; connection.Open(); int recordsInserted = adpt.Update(dtInsertRows); connection.Close(); } private static DataTable GetDataTable() { // You First need a DataTable and have all the insert values in it DataTable dtInsertRows = new DataTable(); dtInsertRows.Columns.Add("NAME"); for (int i = 0; i < 500000; i++) { DataRow drInsertRow = dtInsertRows.NewRow(); string name = "Name : " + i; drInsertRow["NAME"] = name; dtInsertRows.Rows.Add(drInsertRow); } return dtInsertRows; } static void sbc_SqlRowsCopied(object sender, SqlRowsCopiedEventArgs e) { Console.WriteLine("Number of records affected : " + e.RowsCopied.ToString()); } } }

    Read the article

  • How to Resolve Jason issue

    - by Mohammad Nezhad
    I am working in a web scheduling application which uses DayPilot component I started by reading the documentation and use the calendar control. but whenever I do some thing which (fires an event on the Daypilot control) I face with following error An exception was thrown in the server-side event handler: System.InvalidCastException: Instance Of JasonData doesn't hold a double at DayPilot.Jason.JasonData.op_Explicit(JasonData data) at DayPilot.Web.Ui.Events.EventMoveEventArgs..ctor(JasonData parameters, string[] fields, JasonData data) at DayPilot.Web.Ui.DayPilotCalendar.ExecuteEventJASON(String ea) at DayPilot.Web.Ui.DayPilotCalendar.System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent(string ea) at System.Web.UI.Page.PrepareCallback(String callbackControlID) here is the completed code in the ASPX page <DayPilot:DayPilotCalendar ID="DayPilotCalendar1" runat="server" Direction="RTL" Days="7" DataStartField="eventstart" DataEndField="eventend" DataTextField="name" DataValueField="id" DataTagFields="State" EventMoveHandling="CallBack" OnEventMove="DayPilotCalendar1_EventMove" EventEditHandling="CallBack" OnEventEdit="DayPilotCalendar1_EventEdit" EventClickHandling="Edit" OnBeforeEventRender="DayPilotCalendar1_BeforeEventRender" EventResizeHandling="CallBack" OnEventResize="DayPilotCalendar1_EventResize" EventDoubleClickHandling="CallBack" OnEventDoubleClick="DayPilotCalendar1_EventDoubleClick" oncommand="DayPilotCalendar1_Command" and here is the complete codebehind protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) Initialization(); } private void dbUpdateEvent(string id, DateTime start, DateTime end) { // update for move using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString)) { con.Open(); SqlCommand cmd = new SqlCommand("UPDATE [event] SET [eventstart] = @start, [eventend] = @end WHERE [id] = @id", con); cmd.Parameters.AddWithValue("id", id); cmd.Parameters.AddWithValue("start", start); cmd.Parameters.AddWithValue("end", end); cmd.ExecuteNonQuery(); } } private DataTable dbGetEvents(DateTime start, int days) { // get Data SqlDataAdapter da = new SqlDataAdapter("SELECT [id], [name], [eventstart], [eventend], [state], [other] FROM [event] WHERE NOT (([eventend] <= @start) OR ([eventstart] >= @end))", ConfigurationManager.ConnectionStrings["DayPilotTest"].ConnectionString); ; da.SelectCommand.Parameters.AddWithValue("start", start); da.SelectCommand.Parameters.AddWithValue("end", start.AddDays(days)); DataTable dt = new DataTable(); da.Fill(dt); return dt; } protected void DayPilotCalendar1_EventMove(object sender, DayPilot.Web.Ui.Events.EventMoveEventArgs e) { // Drag and Drop dbUpdateEvent(e.Value, e.NewStart, e.NewEnd); DayPilotCalendar1.DataSource = dbGetEvents(DayPilotCalendar1.StartDate, DayPilotCalendar1.Days); DayPilotCalendar1.DataBind(); DayPilotCalendar1.Update(); } private void Initialization() { // first bind DayPilotCalendar1.StartDate = DayPilot.Utils.Week.FirstDayOfWeek(new DateTime(2009, 1, 1)); DayPilotCalendar1.DataSource = dbGetEvents(DayPilotCalendar1.StartDate, DayPilotCalendar1.Days); DataBind(); } protected void DayPilotCalendar1_BeforeEventRender(object sender, BeforeEventRenderEventArgs e) { // change the color based on state if (e.Tag["State"] == "Fixed") { e.DurationBarColor = "Brown"; } } protected void DayPilotCalendar1_EventResize(object sender, DayPilot.Web.Ui.Events.EventResizeEventArgs e) { dbUpdateEvent(e.Value, e.NewStart, e.NewEnd); DayPilotCalendar1.DataSource = dbGetEvents(DayPilotCalendar1.StartDate, DayPilotCalendar1.Days); DayPilotCalendar1.DataBind(); DayPilotCalendar1.Update(); } protected void DayPilotCalendar1_EventDoubleClick(object sender, EventClickEventArgs e) { dbInsertEvent(e.Text , e.Start, e.End, "New", "New Meeting"); DayPilotCalendar1.DataSource = dbGetEvents(DayPilotCalendar1.StartDate, DayPilotCalendar1.Days); DayPilotCalendar1.DataBind(); DayPilotCalendar1.Update(); } note that I remove unnecessary code behinds

    Read the article

  • DataRelation Insert and ForeignKey

    - by Steve
    Guys, I have a winforms application with two DataGridViews displaying a master-detail relationship from my Person and Address tables. Person table has a PersonID field that is auto-incrementing primary key. Address has a PersonID field that is the FK. I fill my DataTables with DataAdapter and set Person.PersonID column's AutoIncrement=true and AutoIncrementStep=-1. I can insert records in the Person DataTable from the DataGridView. The PersonID column displays unique negative values for PersonID. I update the database by calling DataAdapter.Update(PersonTable) and the negative PersonIDs are converted to positive unique values automatically by SQL Server. Here's the rub. The Address DataGridView show the address table which has a DataRelation to Person by PersonID. Inserted Person records have the temporary negative PersonID. I can now insert records into Address via DataGridView and Address.PersonID is set to the negative value from the DataRelation mapping. I call Adapter.Update(AddressTable) and the negative PersonIDs go into the Address table breaking the relationship. How do you guys handle primary/foreign keys using DataTables and master-detail DataGridViews? Thanks! Steve EDIT: After more googling, I found that SqlDataAdapter.RowUpdated event gives me what I need. I create a new command to query the last id inserted by using @@IDENTITY. It works pretty well. The DataRelation updates the Address.PersonID field for me so it's required to Update the Person table first then update the Address table. All the new records insert properly with correct ids in place! Adapter = new SqlDataAdapter(cmd); Adapter.RowUpdated += (s, e) => { if (e.StatementType != StatementType.Insert) return; //set the id for the inserted record SqlCommand c = e.Command.Connection.CreateCommand(); c.CommandText = "select @@IDENTITY id"; e.Row[0] = Convert.ToInt32( c.ExecuteScalar() ); }; Adapter.Fill(this); SqlCommandBuilder sb = new SqlCommandBuilder(Adapter); sb.GetDeleteCommand(); sb.GetUpdateCommand(); sb.GetInsertCommand(); this.Columns[0].AutoIncrement = true; this.Columns[0].AutoIncrementSeed = -1; this.Columns[0].AutoIncrementStep = -1;

    Read the article

  • ExecuteNonQuery on a stored proc causes it to be deleted

    - by FinancialRadDeveloper
    This is a strange one. I have a Dev SQL Server which has the stored proc on it, and the same stored proc when used with the same code on the UAT DB causes it to delete itself! Has anyone heard of this behaviour? SQL Code: -- Check if user is registered with the system IF OBJECT_ID('dbo.sp_is_valid_user') IS NOT NULL BEGIN DROP PROCEDURE dbo.sp_is_valid_user IF OBJECT_ID('dbo.sp_is_valid_user') IS NOT NULL PRINT '<<< FAILED DROPPING PROCEDURE dbo.sp_is_valid_user >>>' ELSE PRINT '<<< DROPPED PROCEDURE dbo.sp_is_valid_user >>>' END go create procedure dbo.sp_is_valid_user @username as varchar(20), @isvalid as int OUTPUT AS BEGIN declare @tmpuser as varchar(20) select @tmpuser = username from CPUserData where username = @username if @tmpuser = @username BEGIN select @isvalid = 1 END else BEGIN select @isvalid = 0 END END GO Usage example DECLARE @isvalid int exec dbo.sp_is_valid_user 'username', @isvalid OUTPUT SELECT valid = @isvalid The usage example work all day... when I access it via C# it deletes itself in the UAT SQL DB but not the Dev one!! C# Code: public bool IsValidUser(string sUsername, ref string sErrMsg) { string sDBConn = ConfigurationSettings.AppSettings["StoredProcDBConnection"]; SqlCommand sqlcmd = new SqlCommand(); SqlDataAdapter sqlAdapter = new SqlDataAdapter(); try { SqlConnection conn = new SqlConnection(sDBConn); sqlcmd.Connection = conn; conn.Open(); sqlcmd.CommandType = CommandType.StoredProcedure; sqlcmd.CommandText = "sp_is_valid_user"; // params to pass in sqlcmd.Parameters.AddWithValue("@username", sUsername); // param for checking success passed back out sqlcmd.Parameters.Add("@isvalid", SqlDbType.Int); sqlcmd.Parameters["@isvalid"].Direction = ParameterDirection.Output; sqlcmd.ExecuteNonQuery(); int nIsValid = (int)sqlcmd.Parameters["@isvalid"].Value; if (nIsValid == 1) { conn.Close(); sErrMsg = "User Valid"; return true; } else { conn.Close(); sErrMsg = "Username : " + sUsername + " not found."; return false; } } catch (Exception e) { sErrMsg = "Error :" + e.Source + " msg: " + e.Message; return false; } }

    Read the article

  • ASP.NET FormView: "Object of type 'System.Int32' cannot be converted to type 'System.String"

    - by Vinzcent
    Hey I have a problem with my FromView. I would like to show some data from a Database Table in my FormView. But some data is from the tupe Int32, while this data should be in a TextBox, a string. How do you convert these Int32's. FormView and my ObjectDataSource <asp:FormView ID="fvDetailOrder" runat="server"> <ItemTemplate> Aantal:<br /> <asp:Label CssClass="txtBox" ID="Label15" runat="server" Text='<%# Eval("COUNT") %>' /><br /> Prijs:<br /> <asp:Label CssClass="txtBox" ID="Label16" runat="server" Text='<%# Eval("PRICE") %>' /><br /> Korting:<br /> <asp:Label CssClass="txtBox" ID="Label17" runat="server" Text='' /><br /> Totaal:<br /> <asp:Label CssClass="txtBox" ID="Label18" runat="server" Text='<%# Eval("AMOUNT") %>' /><br /> Betaald:<br /> <asp:Label CssClass="txtBox" ID="Label19" runat="server" Text='<%# Eval("PAID") %>' /><br /> Datum betaling:<br /> <asp:Label CssClass="txtBox" ID="Label20" runat="server" Text='<%# Eval("PDATE") %>' /><br /> </ItemTemplate> </asp:FormView> <asp:ObjectDataSource ID="objdsOrderID" runat="server" OnSelecting="objdsOrderID_Selecting" SelectMethod="getOrdersByID" TypeName="DAL.OrdersDAL"> <SelectParameters> <asp:Parameter Name="id" Type="Int32" /> </SelectParameters> </asp:ObjectDataSource> My Code behind protected void gvOrdersAdmin_SelectedIndexChanged(object sender, EventArgs e) { fvDetailOrder.DataSource = objdsOrderID; fvDetailOrder.DataBind(); // <-- HERE I GET THE ERROR } protected void objdsOrderID_Selecting(object sender, ObjectDataSourceSelectingEventArgs e) { e.InputParameters["id"] = gvOrdersAdmin.DataKeys[gvOrdersAdmin.SelectedRow.RowIndex].Values[0]; ; } My Data Acces Layer public static DataTable getOrdersByID(string id) { string sql = "SELECT 'AUTHOR' = tblAuthors.FIRSTNAME + ' ' + tblAuthors.LASTNAME, tblBooks.*, tblGenres.*, tblLanguages.*, tblOrders.* FROM tblAuthors INNER JOIN tblBooks ON tblAuthors.AUTHOR_ID = tblBooks.AUTHOR_ID INNER JOIN tblGenres ON tblBooks.GENRE_ID = tblGenres.GENRE_ID INNER JOIN tblLanguages ON tblBooks.LANG_ID = tblLanguages.LANG_ID INNER JOIN tblOrders ON tblBooks.BOOK_ID = tblOrders.BOOK_ID" + " WHERE tblOrders.ID = @id;"; SqlDataAdapter da = new SqlDataAdapter(sql, GetConnectionString()); da.SelectCommand.Parameters["id"].Value = id; DataSet ds = new DataSet(); da.Fill(ds, "Orders"); return ds.Tables["Orders"]; } Thanks a lot, Vincent

    Read the article

  • Executing Stored Procedure for each InputRow + SSIS Script Component.

    - by Nev_Rahd
    Hello, In my Script Component, am trying to execute Stored Procedure = which return multiple rows = of which need to generate output rows. Code as below: /* Microsoft SQL Server Integration Services Script Component * Write scripts using Microsoft Visual C# 2008. * ScriptMain is the entry point class of the script.*/ using System; using System.Data; using System.Data.SqlClient; using Microsoft.SqlServer.Dts.Pipeline.Wrapper; using Microsoft.SqlServer.Dts.Runtime.Wrapper; [Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute] public class ScriptMain : UserComponent { SqlConnection cnn = new SqlConnection(); IDTSConnectionManager100 cnManager; //string cmd; SqlCommand cmd = new SqlCommand(); public override void AcquireConnections(object Transaction) { cnManager = base.Connections.myConnection; cnn = (SqlConnection)cnManager.AcquireConnection(null); } public override void PreExecute() { base.PreExecute(); } public override void PostExecute() { base.PostExecute(); } public override void InputRows_ProcessInputRow(InputRowsBuffer Row) { while(Row.NextRow()) { DataTable dt = new DataTable(); cmd.Connection = cnn; cmd.CommandText = "OSPATTRIBUTE_GetOPNforOP"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@NK", SqlDbType.VarChar).Value = Row.OPNK.ToString(); cmd.Parameters.Add("@EDWSTARTDATE", SqlDbType.DateTime).Value = Row.EDWEFFECTIVESTARTDATETIME; SqlDataAdapter adapter = new SqlDataAdapter(cmd); adapter.Fill(dt); foreach (DataRow dtrow in dt.Rows) { OutputValidBuffer.AddRow(); OutputValidBuffer.OPNK = Row.OPNK; OutputValidBuffer.OSPTYPECODE = Row.OSPTYPECODE; OutputValidBuffer.ORGPROVTYPEDESC = Row.ORGPROVTYPEDESC; OutputValidBuffer.HEALTHSECTORCODE = Row.HEALTHSECTORCODE; OutputValidBuffer.HEALTHSECTORDESCRIPTION = Row.HEALTHSECTORDESCRIPTION; OutputValidBuffer.EDWEFFECTIVESTARTDATETIME = Row.EDWEFFECTIVESTARTDATETIME; OutputValidBuffer.EDWEFFECTIVEENDDATETIME = Row.EDWEFFECTIVEENDDATETIME; OutputValidBuffer.OPQI = Row.OPQI; OutputValidBuffer.OPNNK = dtrow[0].ToString(); OutputValidBuffer.OSPNAMETYPECODE = dtrow[1].ToString(); OutputValidBuffer.NAMETYPEDESC = dtrow[2].ToString(); OutputValidBuffer.OSPNAME = dtrow[3].ToString(); OutputValidBuffer.EDWEFFECTIVESTARTDATETIME1 = Row.EDWEFFECTIVESTARTDATETIME; OutputValidBuffer.EDWEFFECTIVEENDDATETIME1 = Row.EDWEFFECTIVEENDDATETIME; OutputValidBuffer.OPNQI = dtrow[6].ToString(); } } } public override void ReleaseConnections() { cnManager.ReleaseConnection(cnn); } } This is always skipping the first row. while(Row.NextRow()) is always bringing the second row of the input buffer. What am I doing wrong. Thanks

    Read the article

  • Proper binding data to combobox and handling its events.

    - by Wodzu
    Hi guys. I have a table in SQL Server which looks like this: ID Code Name Surname 1 MS Mike Smith 2 JD John Doe 3 UP Unknown Person and so on... Now I want to bind the data from this table into the ComboBox in a way that in the ComboBox I have displayed value from the Code column. I am doing the binding in this way: SqlDataAdapter sqlAdapter = new SqlDataAdapter("SELECT * FROM dbo.Users ORDER BY Code", MainConnection); sqlAdapter.Fill(dsUsers, "Users"); cbxUsers.DataSource = dsUsers.Tables["Users"]; cmUsers = (CurrencyManager)cbxUsers.BindingContext[dsUsers.Tables["Users"]]; cbxUsers.DisplayMember = "Code"; And this code seems to work. I can scroll through the list of Codes. Also I can start to write code by hand and ComboBox will autocomplete the code for me. However, I wanted to put a label at the top of the combobox to display Name and Surname of the currently selected user code. My line of though was like that: "So, I need to find an event which will fire up after the change of code in combobox and in that event I will get the current DataRow..." I was browsing through the events of combobox, tried many of them but without a success. For example: private void cbxUsers_SelectionChangeCommitted(object sender, EventArgs e) { if (cmUsers != null) { DataRowView drvCurrentRowView = (DataRowView)cmUsers.Current; DataRow drCurrentRow = drvCurrentRowView.Row; lblNameSurname.Text = Convert.ToString(drCurrentRow["Name"]) + " " + Convert.ToString(drCurrentRow["Surname"]); } } This give me a strange results. Firstly when I scroll via mouse scroll it doesn't return me the row wich I am expecting to obtain. For example on JD it shows me "Mike Smith", on MS it shows me "John Doe" and on UP it shows me "Mike Smith" again! The other problem is that when I start to type in ComboBox and press enter it doesn't trigger the event. However, everything works as expected when I bind data to lblNameSurname.Text in this way: lblNameSurname.DataBindings.Add("Text", dsusers.Tables["Users"], "Name"); The problem here is that I can bind only one column and I want to have two. I don't want to use two labels for it (one to display name and other to display surname). So, what is the solution to my problem? Also, I have one question related to the data selection in ComboBox. Now, when I type something in the combobox it allows me to type letters that are not existing in the list. For example, I start to type "J" and instead of finishing with "D" so I would have "JD", I type "Jsomerandomtexthere". Combobox will allow that but such item does not exists on the list. In other words, I want combobox to prevent user from typing code which is not on the list of codes. Thanks in advance for your time.

    Read the article

  • Data Access Layer - static list objects and caching

    - by Truegilly
    Hello, i am devloping a site using .net MVC i have a data access layer which basically consists of static list objects that are created from data within my database. The method that rebuilds this data first clears all the list objects. Once they are empty it then add the data. Here is an example of one of the lists im using. its a method which generates all the UK postcodes. there are about 50 methods similar to this in my application that return all sorts of information, such as towns, regions, members, emails etc. public static List<PostCode> AllPostCodes = new List<PostCode>(); when the rebuild method is called it first clears the list. ListPostCodes.AllPostCodes.Clear(); next it re-bulilds the data, by calling the GetAllPostCodes() method /// <summary> /// static method that returns all the UK postcodes /// </summary> public static void GetAllPostCodes() { using (fab_dataContextDataContext db = new fab_dataContextDataContext()) { IQueryable AllPostcodeData = from data in db.PostCodeTables select data; IDbCommand cmd = db.GetCommand(AllPostcodeData); SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = (SqlCommand)cmd; DataSet dataSet = new DataSet(); cmd.Connection.Open(); adapter.FillSchema(dataSet, SchemaType.Source); adapter.Fill(dataSet); cmd.Connection.Close(); // crete the objects foreach (DataRow row in dataSet.Tables[0].Rows) { PostCode postcode = new PostCode(); postcode.ID = Convert.ToInt32(row["PostcodeID"]); postcode.Outcode = row["OutCode"].ToString(); postcode.Latitude = Convert.ToDouble(row["Latitude"]); postcode.Longitude = Convert.ToDouble(row["Longitude"]); postcode.TownID = Convert.ToInt32(row["TownID"]); AllPostCodes.Add(postcode); postcode = null; } } } The rebuild occurs every 1 hour. this ensures that every 1 hour the site will have fresh set of cached data. the issue ive got is that occasionally if during a rebuild, the server will be hit by a request and an exception is thrown. The exception is "Index was outside the bounds of the array." it is due to when a list is being cleared. ListPostCodes.AllPostCodes.Clear(); - // throws exception - although its not always in regard to this list. Once this exception is thrown application dies, All users are affected. I have to restart the server to fix it. i have 2 questions... If i utilise caching instead of static objects would this help ? Is there any way i can say "while the rebuild is taking place, wait for it to complete until accepting requests" any help is most appricaiated ;) truegilly

    Read the article

  • Need help in displaying data insider marquee

    - by user59637
    Hi all, I want to display news inside the marquee markup in my banking application but its not happening.Please somebody help me what is the error in my code.Here is my code: <marquee bgcolor="silver" direction="left" id="marq1" runat="server" behavior="scroll" scrolldelay="80" style="height: 19px" width="565"> <% String se = Session["countnews"].ToString(); for (int i = 0; i < int.Parse("" +se); i++) { %> <strong><%Response.Write("&nbsp;&nbsp;" + Session["news"+i] + "&nbsp;&nbsp;"); %></strong> <% } %> </marquee> public class News { DataSet ds = new DataSet("Bank"); SqlConnection conn; String check; SqlDataAdapter sda; int i; public string News_Name; public int Count_News; public int newsticker() { conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BankingTransaction"].ConnectionString.ToString()); check = "Select NewsTitle from News where NewsStatus = 'A'"; sda = new SqlDataAdapter(check, conn); sda.Fill(ds, "News"); if (ds.Tables[0].Rows.Count > 0) { for (i = 0; i < ds.Tables[0].Rows.Count; i++) { News_Name =i+ ds.Tables[0].Rows[i].ItemArray[0].ToString(); } Count_News = ds.Tables[0].Rows.Count; } else { News_Name =0+ "Welcome to WestSide Bank Online Web site!"; Count_News = 1; } return int.Parse(Count_News.ToString()); } protected void Page_Load(object sender, EventArgs e) { News obj = new News(); try { obj.newsticker(); Session["news"] = obj.News_Name.ToString(); Session["countnews"] = obj.Count_News.ToString(); } catch (SqlException ex) { Response.Write("Error in login" + ex.Message); Response.Redirect("Default.aspx"); } finally { obj = null; } }

    Read the article

  • Login function runs different between local and server

    - by quangnd
    Here is my check login function: protected bool checkLoginStatus(String email, String password) { bool loginStatus = false; bool status = false; try { Connector.openConn(); String str = "SELECT * FROM [User]"; SqlCommand cmd = new SqlCommand(str, Connector.conn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "tblUser"); //check valid foreach (DataRow dr in ds.Tables[0].Rows) { if (email == dr["Email"].ToString() && password == Connector.base64Decode(dr["Password"].ToString())) { Session["login_status"] = true; Session["username"] = dr["Name"].ToString(); Session["userId"] = dr["UserId"].ToString(); status = true; break; } } } catch (Exception ex) { } finally { Connector.closeConn(); } return status; } And call it at my aspx page: String email = Login1.UserName.Trim(); String password = Login1.Password.Trim(); if (checkLoginStatus(email, password)) Response.Redirect(homeSite); else lblFailure.Text = "Invalid!"; I ran this page at localhost successful! When I published it to server, this function only can run if email and password correct! Other, error occured: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) I tried open SQL Server 2008 Configuration Manager and enable SQL Server Browser service (Logon as:NT Authority/Local Service) but it stills error. (note: here is connection string of openConn() at Localhost (run on SQLEXpress 2005) connectionString="Data Source=MYLAPTOP\SQLEXPRESS;Initial Catalog=Spider_Vcms;Integrated Security=True" /> ) At server (run on SQL Server Enterprise 2008) connectionString="Data Source=SVR;Initial Catalog=Spider_Vcms;User Id=abc;password=123456;" /> anyone have an answer for my problem :( thanks a lot!

    Read the article

  • radgridview delete update in asp.net

    - by abhi
    i have written the follwing to display data from the datagrid and den insert new rows but how do i perform update and delete plss help here's my code 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 Telerik.Web.UI; using System.Data.SqlClient; public partial class Default6 : System.Web.UI.Page { string strQry, strCon; SqlDataAdapter da; SqlConnection con; DataSet ds; protected void Page_Load(object sender, EventArgs e) { strCon = "Data Source=MINETDEVDATA; Initial Catalog=ML_SuppliersProd; User Id=sa; Password=@MinetApps7;"; con = new SqlConnection(strCon); strQry = "SELECT * FROM table1"; da = new SqlDataAdapter(strQry, con); SqlCommandBuilder cmdbuild = new SqlCommandBuilder(da); ds = new DataSet(); da.Fill(ds, "table1"); RadGrid1.DataSource = ds.Tables["table1"]; RadGrid1.DataBind(); Label3.Visible = false; Label4.Visible = false; Label5.Visible = false; txtFname.Visible = false; txtLname.Visible = false; txtDesignation.Visible = false; } protected void Submit_Click(object sender, EventArgs e) { Label3.Visible = true; Label4.Visible = true; Label5.Visible = true; txtFname.Visible = true; txtLname.Visible = true; txtDesignation.Visible = true; } protected void Button2_Click(object sender, EventArgs e) { DataSet ds = new DataSet("EmployeeSet"); da.Fill(ds, "table1"); DataTable EmployeeTable = ds.Tables["table1"]; DataRow row = EmployeeTable.NewRow(); row["Fname"] = txtFname.Text.ToString(); row["Lname"] = txtLname.Text.ToString(); row["Designation"] = txtDesignation.Text.ToString(); EmployeeTable.Rows.Add(row); da.Update(ds, "table1"); //RadGrid1.DataSource = ds.Tables["table1"]; //RadGrid1.DataBind(); txtFname.Text = ""; txtLname.Text = ""; txtDesignation.Text = ""; } protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e) { } } }

    Read the article

  • If Then Statement Condition Being Ignored With Optimisations On

    - by Matma
    I think im going mad but can some show me what im missing, it must be some stupidly simple i just cant see the wood for the trees. BOTH side of this if then else statement are being executed? Ive tried commenting out the true side and moving the condition to a seperate variable with the same result. However if i explicitly set the condition to 1=0 or 1=1 then the if then statement is operating as i would expect. i.e. only executing one side of the equation... The only time ive seen this sort of thing is when the compiler has crashed and is no longer compiling (without visible indication that its not) but ive restarted studio with the same results, ive cleaned the solution, built and rebuilt with no change? please show me the stupid mistake im making using vs2005 if it matters. Dim dset As DataSet = New DataSet If (CboCustomers.SelectedValue IsNot Nothing) AndAlso (CboCustomers.SelectedValue <> "") Then Dim Sql As String = "Select sal.SalesOrderNo As SalesOrder,cus.CustomerName,has.SerialNo, convert(varchar,sal.Dateofpurchase,103) as Date from [dbo].[Customer_Table] as cus " & _ " inner join [dbo].[Hasp_table] as has on has.CustomerID=cus.CustomerTag " & _ " inner join [dbo].[salesorder_table] as sal On sal.Hasp_ID =has.Hasp_ID Where cus.CustomerTag = '" & CboCustomers.SelectedValue.ToString & "'" Dim dap As SqlDataAdapter = New SqlDataAdapter(Sql, FormConnection) dap.Fill(dset, "dbo.Customer_Table") DGCustomer.DataSource = dset.Tables("dbo.Customer_Table") Else Dim erm As String = "wtf" End If EDIT: i have found that this is something to do with the release config settings im using, i guesing its the optimisations bit. does anyone know of any utils/addons for vs that show if a line has been optimised out. delphi, my former language showed blue dots in the left margin to show that it was a compiled line, no dot meaning it wasnt compiled in, is there anything like that for vs? alternatively can someone explain how optimisations would affect this simple if statement causeing it to run both sides? EDIT2: using this thread as possible causes/solutions : http://stackoverflow.com/questions/2135509/bug-only-occurring-when-compile-optimization-enabled. It does the same with release = optimisations on, x86, x64 and AnyCPU Goes away with optimisations off. Im using V2005 on a x64 win7 machine, if that matters. Thanks

    Read the article

  • auto complete asp.net

    - by lodun
    Why my autocomplete ajax script does not work: This is my WebService.cs: using System; using System.Data; using System.Web; using System.Collections; using System.Web.Services; using System.Web.Services.Protocols; using System.ComponentModel; using System.Data.SqlClient; using System.Collections.Generic; using System.Configuration; using System.Web.Script.Services; [ScriptService] [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. public class WebService : System.Web.Services.WebService { public WebService () { //Uncomment the following line if using designed components //InitializeComponent(); } [WebMethod] public string[] GetCountryInfo(string prefixText, int count) { string sql = "Select * from questions Where username like @prefixText"; SqlDataAdapter da = new SqlDataAdapter(sql,"estudent_piooConnectionString"); da.SelectCommand.Parameters.Add("@prefixText", SqlDbType.VarChar, 50).Value = prefixText + "%"; DataTable dt = new DataTable(); da.Fill(dt); string[] items = new string[dt.Rows.Count]; int i = 1; foreach (DataRow dr in dt.Rows) { items.SetValue(dr["username"].ToString(),i); i++; } return items; } } my css: /*AutoComplete flyout */ .autocomplete_completionListElement { margin : 0px!important; background-color : inherit; color : windowtext; border : buttonshadow; border-width : 1px; border-style : solid; cursor : 'default'; overflow : auto; height : 200px; text-align : left; list-style-type : none;padding:0px; } /* AutoComplete highlighted item */ .autocomplete_highlightedListItem { background-color: #ffff99; color: black; padding: 1px; } /* AutoComplete item */ .autocomplete_listItem { background-color : window; color : windowtext; padding : 1px; } and textbox: <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> <cc1:AutoCompleteExtender ID="AutoCompleteExtender1" CompletionListCssClass="autocomplete_completionListElement" CompletionListItemCssClass="autocomplete_listItem" CompletionSetCount="20" CompletionInterval="1000" DelimiterCharacters=";,:" CompletionListHighlightedItemCssClass="autocomplete_highlightedList MinimumPrefixLength="1" ServiceMethod="GetCountryInfo" ShowOnlyCurrentWordInCompletionListItem="true" TargetControlID="TextBox2" ServicePath="WebService.asmx" runat="server"></cc1:AutoCompleteExtender>

    Read the article

  • GridView in ASP.NET 2.0

    - by Subho
    How can I populate an editable Grid with data from different tables from MSSQL Server'05 writing a code behind function??? I have used: Dim conn As New SqlConnection(conn_web) Dim objCmd As New SqlDataAdapter(sql, conn) Dim oDS As New DataSet objCmd.Fill(oDS, "TAB") Dim dt As DataTable = oDS.Tables(0) Dim rowCount As Integer = dt.Rows.Count Dim dr As DataRow = dt.NewRow() If rowCount = 0 Then e.DataSource = Nothing e.DataBind() e.Focus() Else e.DataSource = dt e.DataBind() End If

    Read the article

  • How to bind grid in ASP.NET?

    - by Abid Ali
    I cant bind my Grid. I dont know what I am doing wrong, the grid appears empty when I run the program. here is my code :: protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) this.BindGrid(this.GridView1); } private void BindGrid(GridView grid) { SqlCommand cmd = new SqlCommand("Select * from Person", cn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); grid.DataSource = dt; grid.DataBind(); } <body> <form id="form1" runat="server"> <div style="margin-left: 240px"> <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" Width="856px" AutoGenerateColumns = "false" ShowFooter = "true" ShowHeader="true" BorderStyle="Groove" CaptionAlign="Top" HorizontalAlign="Center" onrowdatabound="GridView1_RowDataBound" > <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> <Columns> <asp:BoundField HeaderText="ID" /> <asp:BoundField HeaderText="First Name" /> <asp:BoundField HeaderText="Last Name" /> <asp:BoundField HeaderText="Home Phone #" /> <asp:BoundField HeaderText="Cell #" /> <asp:BoundField HeaderText="Email Address" /> <asp:BoundField HeaderText="NIC #" /> <asp:TemplateField HeaderText="Action"> <ItemTemplate> <asp:Button ID="Button1" runat="server" Text="Button" /> <asp:Button ID="Button2" runat="server" Text="Button" /> </ItemTemplate> </asp:TemplateField> </Columns> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <EditRowStyle BackColor="#999999" /> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> </asp:GridView> </div> </form> </body>

    Read the article

  • Modify values on-the-fly during SqlAdapter.Fill( )

    - by Timothy
    What would the proper way be to modify values on the fly as they are loaded into a DataTable by SqlAdapter.Fill()? I have globalized my application's log messages. An integer indicating the event type and serialized data relevant to the event is stored in the database as show below. When I display the logged events through a DataGridView control to the user, I interpolate the data to a formatting string. event_type event_timestamp event_details ============================================ 3 2010-05-04 20:49:58 jsmith 1 2010-05-04 20:50:42 jsmith ... I am currently iterating through the DataTable's rows to format the messages. public class LogDataTable : DataTable { public LogDataTable() { Locale = CultureInfo.CurrentCulture; Columns.AddRange(new DataColumn[] { new DataColumn("event_type", typeof(Int32)), new DataColumn("event_timestamp", typeof(DateTime)), new DataColumn("event_details", typeof(String))}); } } ... using (SqlDataAdapter adapter = new SqlDataAdapter(...)) { adapter.SelectCommand.Parameters.AddRange(new Object[] { ... }); adapter.Fill(table); } foreach (DataRow row in table.Rows) { switch ((LogEventType)row["event_type"]) { case LogEventType.Create: row["event_details"] = String.Format(Resources.Strings.LogEventCreateMsg, row["event_details"]; break; case LogEventType.Create: row["event_details"] = String.Format(Resources.Strings.LogEventCreateMsg, row["event_details"]; break; ... The end result as displayed would resemble: Type Date and Time Details ==================================================================== [icon] 2010-05-04 20:49:58 Failed login attempt with username jsmith [icon] 2010-05-04 20:50:42 Successful login with username jsmith ... It seems wasteful to iterate the result set twice-- once as the table is filled by the adapter, and again to perform the replacements. I would really like to do the replacement on-the-fly in my LogDataTable class as it is being populated. I have tried overriding an OnRowChanging method in LogDataTable, which throws an InRowChangingEventException. protected override void OnRowChanging(DataRowChangeEventArgs e) { base.OnRowChanging(e); switch ((LogEventType)row["event_type"]) ... I have tried overriding an OnRowChanged method, which throws a StackOverflowException (I assume changing it re-triggers the method ad infinitum?). I have tried overriding an OnTableNewRow method, which does not throw an exception but appears not to be invoked (I assume only when a user adds a row in the view, which I've prevented). I'd greatly appreciate any assistance anyone can give me.

    Read the article

  • I've caught an exception!! Now what?

    - by Jonesy
    Hi folks, I've started using try catch blocks (bit late i know!) but now im not sure what to do with the exception once i've caught it. What do people usually do here? -- Jonesy Try connection.Open() Dim sqlCmd As New SqlCommand("do some SQL", connection) Dim sqlDa As New SqlDataAdapter(sqlCmd) sqlDa.Fill(dt) Catch ex As SQLException ' ahhhh what to do now!!!? Finally connection.Close() End Try

    Read the article

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