Search Results

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

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

  • Alert on gridview edit based on permission

    - by Vicky
    I have a gridview with edit option at the start of the row. Also I maintain a seperate table called Permission where I maintain user permissions. I have three different types of permissions like Admin, Leads, Programmers. These all three will have access to the gridview. Except admin if anyone tries to edit the gridview on clicking the edit option, I need to give an alert like This row has important validation and make sure you make proper changes. When I edit, the action with happen on table called Application. The table has a column called Comments. Also the alert should happen only when they try to edit rows where the Comments column have these values in them. ManLog datas Funding Approved Exported Applications My try so far. public bool IsApplicationUser(string userName) { return CheckUser(userName); } public static bool CheckUser(string userName) { string CS = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString(); DataTable dt = new DataTable(); using (SqlConnection connection = new SqlConnection(CS)) { SqlCommand command = new SqlCommand(); command.Connection = connection; string strquery = "select * from Permissions where AppCode='Nest' and UserID = '" + userName + "'"; SqlCommand cmd = new SqlCommand(strquery, connection); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); } if (dt.Rows.Count >= 1) return true; else return true; } protected void Details_RowCommand(object sender, GridViewCommandEventArgs e) { string currentUser = HttpContext.Current.Request.LogonUserIdentity.Name; string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString(); string[] words = currentUser.Split('\\'); currentUser = words[1]; bool appuser = IsApplicationUser(currentUser); if (appuser) { DataSet ds = new DataSet(); using (SqlConnection connection = new SqlConnection(str)) { SqlCommand command = new SqlCommand(); command.Connection = connection; string strquery = "select Role_Cd from User_Role where AppCode='PM' and UserID = '" + currentUser + "'"; SqlCommand cmd = new SqlCommand(strquery, connection); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds); } if (e.CommandName.Equals("Edit") && ds.Tables[0].Rows[0]["Role_Cd"].ToString().Trim() != "ADMIN") { int index = Convert.ToInt32(e.CommandArgument); GridView gvCurrentGrid = (GridView)sender; GridViewRow row = gvCurrentGrid.Rows[index]; string strID = ((Label)row.FindControl("lblID")).Text; string strAppName = ((Label)row.FindControl("lblAppName")).Text; Response.Redirect("AddApplication.aspx?ID=" + strID + "&AppName=" + strAppName + "&Edit=True"); } } } Kindly let me know if I need to add something. Thanks for any suggestions.

    Read the article

  • how to serialize a DataTable to json or xml

    - by loviji
    Hello, i'm trying to serialize DataTable to Json or XML. is it possibly and how? any tutorials and ideas, please. For example a have a sql table: CREATE TABLE [dbo].[dictTable]( [keyValue] [int] IDENTITY(1,1) NOT NULL, [valueValue] [int] NULL, CONSTRAINT [Psd2Id] PRIMARY KEY CLUSTERED ( [keyValue] ASC )WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY] C# code: string connectionString = "server=localhost;database=dbd;uid=**;pwd=**"; SqlConnection mySqlConnection = new SqlConnection(connectionString); string selectString = "SELECT keyValue, valueValue FROM dicTable"; SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = selectString; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); string dataTableName = "dictionary"; mySqlDataAdapter.Fill(myDataSet, dataTableName); DataTable myDataTable = myDataSet.Tables[dataTableName]; //now how to serialize it?

    Read the article

  • Need help in gridview displaying data

    - by sumit
    Hi all, I want to display all the data in gridview which i am inserting in runtime. For that i have written code but getting this error. "Both DataSource and DataSourceID are defined on 'GridView1'. Remove one definition." protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { BindData(); } } public void BindData() { string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString(); SqlConnection con = new SqlConnection(str); SqlDataAdapter da = new SqlDataAdapter("select * from Items where ItemId='" + TxtItemId.Text + "'", con); DataSet ds = new DataSet(); da.Fill(ds,"Items"); GridView1.DataSource = ds; GridView1.DataBind(); } Pls modify my code where is my mistake. Thanks, Sumit

    Read the article

  • Trouble updating my datagrid in WPF

    - by wrigley06
    As the title indicates, I'm having trouble updating a datagrid in WPF. Basically what I'm trying to accomplish is a datagrid, that is connected to a SQL Server database, that updates automatically once a user enters information into a few textboxes and clicks a submit button. You'll notice that I have a command that joins two tables. The data from the Quote_Data table will be inserted by a different user at a later time. For now my only concern is getting the information from the textboxes and into the General_Info table, and from there into my datagrid. The code, which I'll include below compiles fine, but when I hit the submit button, nothing happens. This is the first application I've ever built working with a SQL Database so many of these concepts are new to me, which is why you'll probably look at my code and wonder what is he thinking. public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } public DataSet mds; // main data set (mds) private void Window_Loaded_1(object sender, RoutedEventArgs e) { try { string connectionString = Sqtm.Properties.Settings.Default.SqtmDbConnectionString; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); //Merging tables General_Info and Quote_Data SqlCommand cmd = new SqlCommand("SELECT General_Info.Quote_ID, General_Info.Open_Quote, General_Info.Customer_Name," + "General_Info.OEM_Name, General_Info.Qty, General_Info.Quote_Num, General_Info.Fab_Drawing_Num, " + "General_Info.Rfq_Num, General_Info.Rev_Num, Quote_Data.MOA, Quote_Data.MOQ, " + "Quote_Data.Markup, Quote_Data.FOB, Quote_Data.Shipping_Method, Quote_Data.Freight, " + "Quote_Data.Vendor_Price, Unit_Price, Quote_Data.Difference, Quote_Data.Vendor_NRE_ET, " + "Quote_Data.NRE, Quote_Data.ET, Quote_Data.STI_NET, Quote_Data.Mfg_Time, Quote_Data.Delivery_Time, " + "Quote_Data.Mfg_Name, Quote_Data.Mfg_Location " + "FROM General_Info INNER JOIN dbo.Quote_Data ON General_Info.Quote_ID = Quote_Data.Quote_ID", connection); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); MainGrid.ItemsSource = dt.DefaultView; mds = new DataSet(); da.Fill(mds, "General_Info"); MainGrid.DataContext = mds.Tables["General_Info"]; } } catch (Exception ex) { MessageBox.Show(ex.Message); } // renaming column names from the database so they are easier to read in the datagrid MainGrid.Columns[0].Header = "#"; MainGrid.Columns[1].Header = "Date"; MainGrid.Columns[2].Header = "Customer"; MainGrid.Columns[3].Header = "OEM"; MainGrid.Columns[4].Header = "Qty"; MainGrid.Columns[5].Header = "Quote Number"; MainGrid.Columns[6].Header = "Fab Drawing Num"; MainGrid.Columns[7].Header = "RFQ Number"; MainGrid.Columns[8].Header = "Rev Number"; MainGrid.Columns[9].Header = "MOA"; MainGrid.Columns[10].Header = "MOQ"; MainGrid.Columns[11].Header = "Markup"; MainGrid.Columns[12].Header = "FOB"; MainGrid.Columns[13].Header = "Shipping"; MainGrid.Columns[14].Header = "Freight"; MainGrid.Columns[15].Header = "Vendor Price"; MainGrid.Columns[16].Header = "Unit Price"; MainGrid.Columns[17].Header = "Difference"; MainGrid.Columns[18].Header = "Vendor NRE/ET"; MainGrid.Columns[19].Header = "NRE"; MainGrid.Columns[20].Header = "ET"; MainGrid.Columns[21].Header = "STINET"; MainGrid.Columns[22].Header = "Mfg. Time"; MainGrid.Columns[23].Header = "Delivery Time"; MainGrid.Columns[24].Header = "Manufacturer"; MainGrid.Columns[25].Header = "Mfg. Location"; } private void submitQuotebtn_Click(object sender, RoutedEventArgs e) { CustomerData newQuote = new CustomerData(); int quantity; quantity = Convert.ToInt32(quantityTxt.Text); string theDate = System.DateTime.Today.Date.ToString("d"); newQuote.OpenQuote = theDate; newQuote.CustomerName = customerNameTxt.Text; newQuote.OEMName = oemNameTxt.Text; newQuote.Qty = quantity; newQuote.QuoteNumber = quoteNumberTxt.Text; newQuote.FdNumber = fabDrawingNumberTxt.Text; newQuote.RfqNumber = rfqNumberTxt.Text; newQuote.RevNumber = revNumberTxt.Text; try { string insertConString = Sqtm.Properties.Settings.Default.SqtmDbConnectionString; using (SqlConnection insertConnection = new SqlConnection(insertConString)) { insertConnection.Open(); SqlDataAdapter adapter = new SqlDataAdapter(Sqtm.Properties.Settings.Default.SqtmDbConnectionString, insertConnection); SqlCommand updateCmd = new SqlCommand("UPDATE General_Info " + "Quote_ID = @Quote_ID, " + "Open_Quote = @Open_Quote, " + "OEM_Name = @OEM_Name, " + "Qty = @Qty, " + "Quote_Num = @Quote_Num, " + "Fab_Drawing_Num = @Fab_Drawing_Num, " + "Rfq_Num = @Rfq_Num, " + "Rev_Num = @Rev_Num " + "WHERE Quote_ID = @Quote_ID"); updateCmd.Connection = insertConnection; System.Data.SqlClient.SqlParameterCollection param = updateCmd.Parameters; // // Add new SqlParameters to the command. // param.AddWithValue("Open_Quote", newQuote.OpenQuote); param.AddWithValue("Customer_Name", newQuote.CustomerName); param.AddWithValue("OEM_Name", newQuote.OEMName); param.AddWithValue("Qty", newQuote.Qty); param.AddWithValue("Quote_Num", newQuote.QuoteNumber); param.AddWithValue("Fab_Drawing_Num", newQuote.FdNumber); param.AddWithValue("Rfq_Num", newQuote.RfqNumber); param.AddWithValue("Rev_Num", newQuote.RevNumber); adapter.UpdateCommand = updateCmd; adapter.Update(mds.Tables[0]); mds.AcceptChanges(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } Thanks in advance to anyone who can help, I really appreciate it, Andrew

    Read the article

  • Updating a Data Source with a Dataset

    - by Paul
    Hi, I need advice. I have asp.net web service and winforms client app. Client call this web method and get dataset. 1. [WebMethod] 2. public DataSet GetSecureDataSet(string id) 3. { 4. 5. 6. SqlConnection conn = null; 7. SqlDataAdapter da = null; 8. DataSet ds; 9. try 10. { 11. 12. string sql = "SELECT * FROM Tab1"; 13. 14. string connStr = WebConfigurationManager.ConnectionStrings["Employees"].ConnectionString; 15. 16. conn = new SqlConnection(connStr); 17. conn.Open(); 18. 19. da = new SqlDataAdapter(sql, conn); 20. 21. ds = new DataSet(); 22. da.Fill(ds, "Tab1"); 23. 24. return ds; 25. } 26. catch (Exception ex) 27. { 28. throw ex; 29. } 30. finally 31. { 32. if (conn != null) 33. conn.Close(); 34. if (da != null) 35. da.Dispose(); 36. } 37. } After he finish work he call this update web method. He can add, delete and edit rows in table in dataset. [WebMethod] public bool SecureUpdateDataSet(DataSet ds) { SqlConnection conn = null; SqlDataAdapter da = null; SqlCommand cmd = null; try { DataTable delRows = ds.Tables[0].GetChanges(DataRowState.Deleted); DataTable addRows = ds.Tables[0].GetChanges(DataRowState.Added); DataTable editRows = ds.Tables[0].GetChanges(DataRowState.Modified); string sql = "UPDATE * FROM Tab1"; string connStr = WebConfigurationManager.ConnectionStrings["Employees"].ConnectionString; conn = new SqlConnection(connStr); conn.Open(); cmd = new SqlCommand(sql, conn); da = new SqlDataAdapter(sql, conn); if (addRows != null) { da.Update(addRows); } if (delRows != null) { da.Update(delRows); } if (editRows != null) { da.Update(editRows); } return true; } catch (Exception ex) { throw ex; } finally { if (conn != null) conn.Close(); if (da != null) da.Dispose(); } } Code on client side 1. //on client side is dataset bind to datagridview 2. Dataset ds = proxy.GetSecureDataSet(""); 3. ds.AcceptChanges(); 4. 5. //edit dataset 6. 7. 8. //get changes 9. DataSet editDataset = ds.GetChanges(); 10. 11. //call update webmethod 12. proxy.SecureUpdateDataSet(editDataSet) But it finish with this error : System.Web.Services.Protocols.SoapException: Server was unable to process request. --- System.InvalidOperationException: Update requires a valid UpdateCommand when passed DataRow collection with modified rows. at WebService.Service.SecureUpdateDataSet(DataSet ds) in D:\Diploma.Work\WebService\Service1.asmx.cs:line 489 Problem is with SQL Commad, client can add, delete and insert row, how can write a corect SQL command.... any advice please? Thank you

    Read the article

  • How can you name the Dataset's Tables you return in a stored proc ?

    - by Brann
    I've got the following stored procedure Create procedure psfoo () AS select * from tbA select * from tbB I'm then accessing the data this way : Sql Command mySqlCommand = new SqlCommand("psfoo" , DbConnection) DataSet ds = new DataSet(); mySqlCommand.CommandType = CommandType.StoredProcedure; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; mySqlDataAdapter.Fill(ds); Now, when I want to access my tables, I have to do this : DataTable datatableA = ds.Tables[0]; DataTable datatableB = ds.Tables[1]; the dataset Tables property also got an accessor by string (instead of int). Is it possible so specify the name of the tables in the SQL code, so that I can instead write this : DataTable datatableA = ds.Tables["NametbA"]; DataTable datatableB = ds.Tables["NametbB"]; I'm using SQL server 2008, if that makes a difference.

    Read the article

  • Call server side method from JSON

    - by Zerotoinfinite
    How to call a method on a server side from JSON. Below is the code I am using SERVER SIDE: [WebMethod] private void GetCustomer( string NoOfRecords) { string connString = "Data Source=Something;Initial Catalog=AdventureWorks;Trusted_Connection=True;"; SqlConnection sCon = new SqlConnection(connString); SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Sales.Customer WHERE CustomerID < '" + NoOfRecords+ "' ", sCon); DataSet ds = new DataSet(); da.Fill(ds); GvDetails.DataSource = ds.Tables[0]; GvDetails.DataBind(); } On Client Side: var txtID = document.getElementById('txtValue'); $.ajax({ type: "POST", url: "Default.aspx/GetCustomer", data: "{Seconds:'" + txtID +"'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(response) { alert(response); } }); Now I want that on button click, I would call the function at the client side [JSON], which pass the textbox value to the function. Please help

    Read the article

  • Problem with filling dataset

    - by Brian
    This is a small portion of my code file. Each time my debugger reaches the line 'NewDA.Fill(NewDS);' at runtime it jumps to the catch. I'm positive the daynumber variable gets a value that's present in the database and I've tried the query outside of the codefile on my database and it works fine. I'm also using the connectionstring 'db' on more parts of the code with successful results. string QueryNew = "SELECT activityname AS [Name], activitycategorynumber AS [Category] " + "FROM ACTIVITY WHERE daynumber = @daynumber"; SqlCommand NewCmd = new SqlCommand(QueryNew, db); NewCmd.Parameters.Add("@daynumber", SqlDbType.Int).Value = daynumber; SqlDataAdapter NewDA = new SqlDataAdapter(NewCmd); DataSet NewDS = new DataSet(); NewDA.Fill(NewDS);

    Read the article

  • Procedure or function expects parameter which was not supplied

    - by eftpotrm
    Driving me mad on a personal project; I know I've done this before but elsewhere and don't have the code. As far as I can see, I'm setting the parameter, I'm setting its value, the connection is open, yet when I try to fill the dataset I get the error 'Procedure or function expects parameter "@test" which was not supplied'. (This is obviously a simplified test! Same error on this or the real, rather longer code though.) C#: SqlCommand l_oCmd; DataSet l_oPage = new DataSet(); l_oCmd = new SqlCommand("usp_test", g_oConn); l_oCmd.Parameters.Add(new SqlParameter("@test", SqlDbType.NVarChar)); l_oCmd.Parameters[0].Value = "hello world"; SqlDataAdapter da = new SqlDataAdapter(l_oCmd); da.Fill(l_oPage); SQL: create procedure usp_test ( @test nvarchar(1000) ) as select @test What have I missed?

    Read the article

  • drop down list had zero value

    - by KareemSaad
    I had ddl which in selected changed it execute some code but when i tried to do that it wasn't worked well WHEN i checked the reason i found that ddl in selected value =0 also i made all well and this is my code protected void DDlProductFamily_SelectedIndexChanged(object sender, EventArgs e) { if (DDlProductFamily.DataValueField.Contains("ProductCategory_Id")) using (SqlConnection Con = Connection.GetConnection()) { SqlCommand Com = new SqlCommand("GetListViewByProductCategory", Con); Com.CommandType = CommandType.StoredProcedure; Com.Parameters.Add(Parameter.NewInt("@ProductCategory_Id", DDlProductFamily.SelectedValue.ToString())); SqlDataAdapter DA = new SqlDataAdapter(Com); DA.Fill(dt); DataList1.DataSource = dt; DataList1.DataBind(); } }

    Read the article

  • Need to get Multiple tables from SqlServer at a time

    - by narmadha
    Hi ,I am working with C#.net,I am using cursor concept in my storedprocedure,While executing it in Sqlserver it is showing Multiple tables,but it is not returning multiple Tables in the code,it is returning only the first table,The following is the code which i have used: DataSet ds = new DataSet("table1"); using (SqlConnection connection = new SqlConnection(connectionstring)) { using (SqlDataAdapter da = new SqlDataAdapter("getworkpersondetails_Orderidwise", connection)) { da.SelectCommand.CommandType = CommandType.StoredProcedure; SqlParameter param; param = new SqlParameter("@OrderId", SqlDbType.Int); param.Value = OrderId; da.SelectCommand.Parameters.Add(param); param = new SqlParameter("@CompanyId", SqlDbType.Int); param.Value = CompanyId; da.SelectCommand.Parameters.Add(param); connection.Open(); da.Fill(ds); connection.Close(); return ds; } }

    Read the article

  • Setting SqlParameter value automatically with DataGridView?

    - by johansson
    Is there a way to set a SqlParameter's value with DataGridView, if data-bound? For example: SqlCommand selCmd = CreateCommand("SELECT * FROM table1"); SqlCommand updCmd = CreateCommand("UPDATE table1 Set column1 = @column1 WHERE id = @id"); updCmd.Parameters.Add(new SqlParameter("column1"), SqlDbTypes.Int)); updCmd.Parameters.Add(new SqlParameter("id", SqlDbTypes.Int)); SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = selCmd; da.UpdateCommand = updCmd; da.Fill(_dataTable); dgv.DataSource = _dataTable; Then somewhere later: da.Update(); How can I make sure it's getting the right column1 value that was edited and the right id for the row for the da.Update(); to work, otherwise it complains that I have not provided the value. Or if there's a better way, please advise. Thanks!

    Read the article

  • dropdown list selected index changed

    - by KareemSaad
    I did my drop down list that get it,s values from database and when run the application it didnot work and compiler didnot see the code onselectedindexchanged="DDlProductFamily_SelectedIndexChanged" protected void DDlProductFamily_SelectedIndexChanged(object sender, EventArgs e) { using (SqlConnection Con = Connection.GetConnection()) { SqlCommand Com = new SqlCommand("SelectThumbByProductFamily", Con); Com.CommandType = CommandType.StoredProcedure; Com.Parameters.Add(Parameter.NewInt("@ProductCategory_Id", DDlProductFamily.SelectedValue.ToString())); SqlDataAdapter DA = new SqlDataAdapter(Com); DA.Fill(dt); DataList1.DataSource = dt; DataList1.DataBind(); } }

    Read the article

  • Dtaset holds a table called "Table", not the table I pass in?

    - by dotnetdev
    Hi, I have the code below: string SQL = "select * from " + TableName; using (DS = new DataSet()) using (SqlDataAdapter adapter = new SqlDataAdapter()) using (SqlConnection sqlconn = new SqlConnection(connectionStringBuilder.ToString())) using (SqlCommand objCommand = new SqlCommand(SQL, sqlconn)) { sqlconn.Open(); adapter.SelectCommand = objCommand; adapter.Fill(DS); } System.Windows.Forms.MessageBox.Show(DS.Tables[0].TableName); return DS; However, every time I run this code, the dataset (DS) is filled with one table called "Table". It does not represent the table name I pass in as the parameter TableName and this parameter does not get mutated so I don't know where the name Table comes from. I'd expect the table to be the same as the tableName parameter I pass in? Any idea why this is not so? Thanks

    Read the article

  • check compiler with break point

    - by KareemSaad
    When I tried to focus on compiler in code i made break point on code if (!IsPostBack) { using (SqlConnection Con = Connection.GetConnection()) { if (Request.QueryString["Category_Id"] != null && DDlProductFamily.SelectedIndex < 0) { SqlCommand Com = new SqlCommand("SelectAllCtageories_Front", Con); Com.CommandType = CommandType.StoredProcedure; Com.Parameters.Add(Parameter.NewInt("@Category_Id", Request.QueryString["Category_Id"])); SqlDataAdapter DA = new SqlDataAdapter(Com); DA.Fill(dt); DataList1.DataSource = dt; DataList1.DataBind(); } but I cannot check condition although I had the value of query string List item

    Read the article

  • Read [for xml auto, elements] into DataTable in ADO.NET

    - by ihorko
    Hello All! I have MS SQL Server stored procedure that returns XML (it uses SELECT with for xml auto, elements) I tried read it into DataTable: DataTable retTable = new DataTable(); SqlCommand comm = new SqlCommand("exec MySP", connection); SqlDataAdapter da = new SqlDataAdapter(comm); connection.Open(); da.Fill(retTable); but retTable contains 12 rows with separated full xml thar SQL Server returns. How can I read that XML from DB into DataTable object? Thanks!

    Read the article

  • Not getting return value

    - by scottO
    I am trying to get a return value and it keeps giving me an error. I am trying to grab the "roleid" after the username has been validated by sending it the username-- I can't figure out what I am doing wrong? public string ValidateRole(string sUsername) { string matchstring = "SELECT roleid FROM tblUserRoles WHERE UserName='" + sUsername +"'"; SqlCommand cmd = new SqlCommand(matchstring); cmd.Connection = new SqlConnection("Data Source=(local);Initial Catalog="mydatabase";Integrated Security=True"); cmd.Connection.Open(); cmd.CommandType = CommandType.Text; SqlDataAdapter sda = new SqlDataAdapter(); DataTable dt = new DataTable(); sda.SelectCommand = cmd; sda.Fill(dt); string match; if (dt.Rows.Count > 0) { foreach (DataRow row in dt.Rows) { match = row["roleid"].ToString(); return match; } } else { match = "fail"; return match; } }

    Read the article

  • using Generics in C# [closed]

    - by Uphaar Goyal
    I have started looking into using generics in C#. As an example what i have done is that I have an abstract class which implements generic methods. these generic methods take a sql query, a connection string and the Type T as parameters and then construct the data set, populate the object and return it back. This way each business object does not need to have a method to populate it with data or construct its data set. All we need to do is pass the type, the sql query and the connection string and these methods do the rest.I am providing the code sample here. I am just looking to discuss with people who might have a better solution to what i have done. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using MWTWorkUnitMgmtLib.Business; using System.Collections.ObjectModel; using System.Reflection; namespace MWTWorkUnitMgmtLib.TableGateway { public abstract class TableGateway { public TableGateway() { } protected abstract string GetConnection(); protected abstract string GetTableName(); public DataSet GetDataSetFromSql(string connectionString, string sql) { DataSet ds = null; using (SqlConnection connection = new SqlConnection(connectionString)) using (SqlCommand command = connection.CreateCommand()) { command.CommandText = sql; connection.Open(); using (ds = new DataSet()) using (SqlDataAdapter adapter = new SqlDataAdapter(command)) { adapter.Fill(ds); } } return ds; } public static bool ContainsColumnName(DataRow dr, string columnName) { return dr.Table.Columns.Contains(columnName); } public DataTable GetDataTable(string connString, string sql) { DataSet ds = GetDataSetFromSql(connString, sql); DataTable dt = null; if (ds != null) { if (ds.Tables.Count 0) { dt = ds.Tables[0]; } } return dt; } public T Construct(DataRow dr, T t) where T : class, new() { Type t1 = t.GetType(); PropertyInfo[] properties = t1.GetProperties(); foreach (PropertyInfo property in properties) { if (ContainsColumnName(dr, property.Name) && (dr[property.Name] != null)) property.SetValue(t, dr[property.Name], null); } return t; } public T GetByID(string connString, string sql, T t) where T : class, new() { DataTable dt = GetDataTable(connString, sql); DataRow dr = dt.Rows[0]; return Construct(dr, t); } public List GetAll(string connString, string sql, T t) where T : class, new() { List collection = new List(); DataTable dt = GetDataTable(connString, sql); foreach (DataRow dr in dt.Rows) collection.Add(Construct(dr, t)); return collection; } } }

    Read the article

  • Sending changes from multiple tables in disconnected dataset to SQLServer...

    - by Stecy
    We have a third party application that accept calls using an XML RPC mechanism for calling stored procs. We send a ZIP-compressed dataset containing multiple tables with a bunch of update/delete/insert using this mechanism. On the other end, a CLR sproc decompress the data and gets the dataset. Then, the following code gets executed: using (var conn = new SqlConnection("context connection=true")) { if (conn.State == ConnectionState.Closed) conn.Open(); try { foreach (DataTable table in ds.Tables) { string columnList = ""; for (int i = 0; i < table.Columns.Count; i++) { if (i == 0) columnList = table.Columns[0].ColumnName; else columnList += "," + table.Columns[i].ColumnName; } var da = new SqlDataAdapter("SELECT " + columnList + " FROM " + table.TableName, conn); var builder = new SqlCommandBuilder(da); builder.ConflictOption = ConflictOption.OverwriteChanges; da.RowUpdating += onUpdatingRow; da.Update(ds, table.TableName); } } catch (....) { ..... } } Here's the event handler for the RowUpdating event: public static void onUpdatingRow(object sender, SqlRowUpdatingEventArgs e) { if ((e.StatementType == StatementType.Update) && (e.Command == null)) { e.Command = CreateUpdateCommand(e.Row, sender as SqlDataAdapter); e.Status = UpdateStatus.Continue; } } and the CreateUpdateCommand method: private static SqlCommand CreateUpdateCommand(DataRow row, SqlDataAdapter da) { string whereClause = ""; string setClause = ""; SqlConnection conn = da.SelectCommand.Connection; for (int i = 0; i < row.Table.Columns.Count; i++) { char quoted; if ((row.Table.Columns[i].DataType == Type.GetType("System.String")) || (row.Table.Columns[i].DataType == Type.GetType("System.DateTime"))) quoted = '\''; else quoted = ' '; string val = row[i].ToString(); if (row.Table.Columns[i].DataType == Type.GetType("System.Boolean")) val = (bool)row[i] ? "1" : "0"; bool isPrimaryKey = false; for (int j = 0; j < row.Table.PrimaryKey.Length; j++) { if (row.Table.PrimaryKey[j].ColumnName == row.Table.Columns[i].ColumnName) { if (whereClause != "") whereClause += " AND "; if (row[i] == DBNull.Value) whereClause += row.Table.Columns[i].ColumnName + "=NULL"; else whereClause += row.Table.Columns[i].ColumnName + "=" + quoted + val + quoted; isPrimaryKey = true; break; } } /* Only values for column that is not a primary key can be modified */ if (!isPrimaryKey) { if (setClause != "") setClause += ", "; if (row[i] == DBNull.Value) setClause += row.Table.Columns[i].ColumnName + "=NULL"; else setClause += row.Table.Columns[i].ColumnName + "=" + quoted + val + quoted; } } return new SqlCommand("UPDATE " + row.Table.TableName + " SET " + setClause + " WHERE " + whereClause, conn); } However, this is really slow when we have a lot of records. Is there a way to optimize this or an entirely different way to send lots of udpate/delete on several tables? I would really much like to use TSQL for this but can't figure a way to send a dataset to a regular sproc. Additional notes: We cannot directly access the SQLServer database. We tried without compression and it was slower.

    Read the article

  • Can anyone help convert this VB Webservice?

    - by CraigJSte
    I can't figure it out for the life of me.. I'm using SQL DataSet Query to iterate to a Class Object which acts as a Data Model for Flex... Initially I used VB.net but now need to convert to C#.. This conversion is done except for the last section where I create a DataRow arow and then try to add the DataSet Values to the Class (Results Class)... I get an error message.. 'VTResults.Results.Ticker' is inaccessible due to its protection level (this is down at the bottom) using System; using System.Web; using System.Collections; using System.Web.Services; using System.Web.Services.Protocols; using System.Data; using System.Data.SqlClient; using System.Configuration; /// <summary> /// Summary description for VTResults /// </summary> [WebService(Namespace = "http://velocitytrading.net/ResultsVT.aspx")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class VTResults : System.Web.Services.WebService { public class Results { string Ticker; string BuyDate; decimal Buy; string SellDate; decimal Sell; string Profit; decimal Period; } [WebMethod] public Results[] GetResults() { string conn = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString; SqlConnection myconn = new SqlConnection(conn); SqlCommand mycomm = new SqlCommand(); SqlDataAdapter myda = new SqlDataAdapter(); DataSet myds = new DataSet(); mycomm.CommandType = CommandType.StoredProcedure; mycomm.Connection = myconn; mycomm.CommandText = "dbo.Results"; myconn.Open(); myda.SelectCommand = mycomm; myda.Fill(myds); myconn.Close(); myconn.Dispose(); int i = 0; Results[] dts = new Results[myds.Tables[0].Rows.Count]; foreach(DataRow arow in myds.Tables[0].Rows) { dts[i] = new Results(); dts[i].Ticker = arow["Ticker"]; dts[i].BuyDate = arow["BuyDate"]; dts[1].Buy = arow["Buy"]; dts[i].SellDate = arow["SellDate"]; dts[i].Sell = arow["Sell"]; dts[i].Profit = arow["Profit"]; dts[i].Period = arow["Period"]; i+=1; } return dts; } } The VB.NET WEBSERVICE that runs fine which I am trying to convert to C# is here. Imports System.Web Imports System.Web.Services Imports System.Web.Services.Protocols Imports System.Data Imports System.Data.SqlClient <WebService(Namespace:="http://localhost:2597/Results/ResultsVT.aspx")> _ <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _ <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Public Class VTResults Inherits System.Web.Services.WebService Public Class Results Public Ticker As String Public BuyDate As String Public Buy As Decimal Public SellDate As String Public Sell As Decimal Public Profit As String Public Period As Decimal End Class <WebMethod()> _ Public Function GetResults() As Results() Try Dim conn As String = ConfigurationManager.ConnectionStrings("LocalSqlServer").ConnectionString Dim myconn = New SqlConnection(conn) Dim mycomm As New SqlCommand Dim myda As New SqlDataAdapter Dim myds As New DataSet mycomm.CommandType = CommandType.StoredProcedure mycomm.Connection = myconn mycomm.CommandText = "dbo.Results" myconn.Open() myda.SelectCommand = mycomm myda.Fill(myds) myconn.Close() myconn.Dispose() Dim i As Integer i = 0 Dim dts As Results() = New Results(myds.Tables(0).Rows.Count - 1) {} Dim aRow As DataRow For Each aRow In myds.Tables(0).Rows dts(i) = New Results dts(i).Ticker = aRow("Ticker") dts(i).BuyDate = aRow("BuyDate") dts(i).Buy = aRow("Buy") dts(i).SellDate = aRow("SellDate") dts(i).Sell = aRow("Sell") dts(i).Profit = aRow("Profit") dts(i).Period = aRow("Period") i += 1 Next Return dts Catch ex As DataException Throw ex End Try End Function End Class

    Read the article

  • C# Can anyone help convert this VB Webservice?

    - by CraigJSte
    I can't figure it out for the life of me.. I'm using SQL DataSet Query to iterate to a Class Object which acts as a Data Model for Flex... Initially I used VB.net but now need to convert to C#.. This conversion is done except for the last section where I create a DataRow arow and then try to add the DataSet Values to the Class (Results Class)... I get an error message.. 'VTResults.Results.Ticker' is inaccessible due to its protection level (this is down at the bottom) using System; using System.Web; using System.Collections; using System.Web.Services; using System.Web.Services.Protocols; using System.Data; using System.Data.SqlClient; using System.Configuration; /// <summary> /// Summary description for VTResults /// </summary> [WebService(Namespace = "http://velocitytrading.net/ResultsVT.aspx")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class VTResults : System.Web.Services.WebService { public class Results { string Ticker; string BuyDate; decimal Buy; string SellDate; decimal Sell; string Profit; decimal Period; } [WebMethod] public Results[] GetResults() { string conn = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString; SqlConnection myconn = new SqlConnection(conn); SqlCommand mycomm = new SqlCommand(); SqlDataAdapter myda = new SqlDataAdapter(); DataSet myds = new DataSet(); mycomm.CommandType = CommandType.StoredProcedure; mycomm.Connection = myconn; mycomm.CommandText = "dbo.Results"; myconn.Open(); myda.SelectCommand = mycomm; myda.Fill(myds); myconn.Close(); myconn.Dispose(); int i = 0; Results[] dts = new Results[myds.Tables[0].Rows.Count]; foreach(DataRow arow in myds.Tables[0].Rows) { dts[i] = new Results(); dts[i].Ticker = arow["Ticker"]; dts[i].BuyDate = arow["BuyDate"]; dts[1].Buy = arow["Buy"]; dts[i].SellDate = arow["SellDate"]; dts[i].Sell = arow["Sell"]; dts[i].Profit = arow["Profit"]; dts[i].Period = arow["Period"]; i+=1; } return dts; } } The VB.NET WEBSERVICE that runs fine which I am trying to convert to C# is here. Imports System.Web Imports System.Web.Services Imports System.Web.Services.Protocols Imports System.Data Imports System.Data.SqlClient <WebService(Namespace:="http://localhost:2597/Results/ResultsVT.aspx")> _ <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _ <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Public Class VTResults Inherits System.Web.Services.WebService Public Class Results Public Ticker As String Public BuyDate As String Public Buy As Decimal Public SellDate As String Public Sell As Decimal Public Profit As String Public Period As Decimal End Class <WebMethod()> _ Public Function GetResults() As Results() Try Dim conn As String = ConfigurationManager.ConnectionStrings("LocalSqlServer").ConnectionString Dim myconn = New SqlConnection(conn) Dim mycomm As New SqlCommand Dim myda As New SqlDataAdapter Dim myds As New DataSet mycomm.CommandType = CommandType.StoredProcedure mycomm.Connection = myconn mycomm.CommandText = "dbo.Results" myconn.Open() myda.SelectCommand = mycomm myda.Fill(myds) myconn.Close() myconn.Dispose() Dim i As Integer i = 0 Dim dts As Results() = New Results(myds.Tables(0).Rows.Count - 1) {} Dim aRow As DataRow For Each aRow In myds.Tables(0).Rows dts(i) = New Results dts(i).Ticker = aRow("Ticker") dts(i).BuyDate = aRow("BuyDate") dts(i).Buy = aRow("Buy") dts(i).SellDate = aRow("SellDate") dts(i).Sell = aRow("Sell") dts(i).Profit = aRow("Profit") dts(i).Period = aRow("Period") i += 1 Next Return dts Catch ex As DataException Throw ex End Try End Function End Class

    Read the article

  • problem with radgrid in pageindexchange event

    - by user203127
    Hi, I Have radgrid in my page. When i turn off view state and in pageindexchanged event when click next page i am getting nothing. Simply a blank page. But when i turn on view state I am getting data in next pages. Is there any way to get the data. I cant turn on the view state due to performance issue. Please see the code below for the reference. .aspx <telerik:RadGrid ID="RadGrid1" OnSortCommand="RadGrid1_SortCommand" OnPageIndexChanged="RadGrid1_PageIndexChanged" AllowSorting="True" PageSize="20" ShowGroupPanel="True" AllowPaging="True" AllowMultiRowSelection="True" AllowFilteringByColumn="true" AutoGenerateColumns="false" EnableViewState="false" runat="server" GridLines="None" OnItemUpdated="RadGrid1_ItemUpdated" OnDataBound="RadGrid1_DataBound"> aspx.cs public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { LoadData(); } private void LoadData() { SqlConnection SqlConn = new SqlConnection("uid=tempuser;password=tempuser;data source=USWASHL10015\\SQLEXPRESS;database=CCOM;"); SqlCommand cmd = new SqlCommand(); cmd.Connection = SqlConn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "usp_testing"; SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); RadGrid1.DataSource = ds; RadGrid1.DataBind(); //RadGrid1.ClientSettings.AllowDragToGroup = true; } protected void RadGrid1_PageIndexChanged(object source, Telerik.Web.UI.GridPageChangedEventArgs e) { //RadGrid1.Rebind(); LoadData(); }

    Read the article

  • SQL statement with datetimepicker

    - by David Archer
    This should hopefully be a simple one. When using a date time picker in a windows form, I want an SQL statement to be carried out, like so: string sql = "SELECT * FROM Jobs WHERE JobDate = '" + dtpJobDate.Text + "'"; Unfortunately, this doesn't actually provide any results because the JobDate field is stored as a DateTime value. I'd like to be able to search for all records that are on this date, no matter what the time stored may be, any help? New query: SqlDataAdapter da2 = new SqlDataAdapter(); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "SELECT * FROM Jobs WHERE JobDate >= @p_StartDate AND JobDate < @p_EndDate"; cmd.Parameters.Add ("@p_StartDate", SqlDbType.DateTime).Value = dtpJobDate.Value.Date; cmd.Parameters.Add ("@p_EndDate", SqlDbType.DateTime).Value = dtpJobDate.Value.Date.AddDays(1); cmd.Connection = conn; da2.SelectCommand = cmd; da2.Fill(dt); dgvJobDiary.DataSource = dt; Huge thanks for all the help!

    Read the article

  • ASP.Net GridView UpdatePanel Paging Gives Error On Second Click

    - by joe
    I'm trying to implement a GridView with paging inside a UpdatePanel. Everything works great when I do my first click. The paging kicks in and the next set of data is loaded quickly. However, when I then try to click a link for another page of data, I get the following error: Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 12030 aspx code <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <contenttemplate> <asp:GridView ID="GridView1" runat="server" CellPadding="2" AllowPaging="true" AllowSorting="true" PageSize="20" OnPageIndexChanging="GridView1_PageIndexChanging" OnSorting="GridView1_PageSorting" AutoGenerateColumns="False"> <Columns> <asp:BoundField DataField="ActivityLogID" HeaderText="Activity Log ID" SortExpression="ActivityLogID" /> <asp:BoundField DataField="ActivityDate" HeaderText="Activity Date" SortExpression="ActivityDate" /> <asp:BoundField DataField="ntUserID" HeaderText="NTUserID" SortExpression="ntUserID" /> <asp:BoundField DataField="ActivityStatus" HeaderText="Activity Status" SortExpression="ActivityStatus" /> </Columns> </asp:GridView> </contenttemplate> </asp:UpdatePanel> code behind private void bindGridView(string sortExp, string sortDir) { SqlCommand mySqlCommand = new SqlCommand(sSQL, mySQLconnection); SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlCommand); mySqlAdapter.Fill(dtDataTable); DataView myDataView = new DataView(); myDataView = dt.DefaultView; if (sortExp != string.Empty) { myDataView.Sort = string.Format("{0} {1}", sortExp, sortDir); } GridView1.DataSource = myDataView; GridView1.DataBind(); if (mySQLconnection.State == ConnectionState.Open) { mySQLconnection.Close(); } } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView1.PageIndex = e.NewPageIndex; bindGridView(); } protected void GridView1_PageSorting(object sender, GridViewSortEventArgs e) { bindGridView(e.SortExpression, sortOrder); } any clues on what is causing the error on the second click?

    Read the article

  • SQL Cache Dependency not working with Stored Procedure

    - by pjacko
    Hello, I can't get SqlCacheDependency to work with a simple stored proc (SQL Server 2008): create proc dbo.spGetPeteTest as set ANSI_NULLS ON set ANSI_PADDING ON set ANSI_WARNINGS ON set CONCAT_NULL_YIELDS_NULL ON set QUOTED_IDENTIFIER ON set NUMERIC_ROUNDABORT OFF set ARITHABORT ON select Id, Artist, Album from dbo.PeteTest And here's my ASP.NET code (3.5 framework): -- global.asax protected void Application_Start(object sender, EventArgs e) { string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString; System.Data.SqlClient.SqlDependency.Start(connectionString); } -- Code-Behind private DataTable GetAlbums() { string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["UnigoConnection"].ConnectionString; DataTable dtAlbums = new DataTable(); using (SqlConnection connection = new SqlConnection(connectionString)) { // Works using select statement, but NOT SP with same text //SqlCommand command = new SqlCommand( // "select Id, Artist, Album from dbo.PeteTest", connection); SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandType = CommandType.StoredProcedure; command.CommandText = "dbo.spGetPeteTest"; System.Web.Caching.SqlCacheDependency new_dependency = new System.Web.Caching.SqlCacheDependency(command); SqlDataAdapter DA1 = new SqlDataAdapter(); DA1.SelectCommand = command; DataSet DS1 = new DataSet(); DA1.Fill(DS1); dtAlbums = DS1.Tables[0]; Cache.Insert("Albums", dtAlbums, new_dependency); } return dtAlbums; } Anyone have any luck with getting this to work with SPs? Thanks!

    Read the article

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