Search Results

Search found 333 results on 14 pages for 'datarow'.

Page 3/14 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Unit Testing VS 2008 Using Excel

    - by David
    When using Excel (2003) to provide data for my unit tests it seems to think that when a cell has TRUE / FALSE value that it is null when there has been no preceding cell values e.g. if (TestContext.DataRow["SatisfactionExtremelySatisfied"] != DBNull.Value) model.SatisfactionExtremelySatisfied = (bool)TestContext.DataRow ["SatisfactionExtremelySatisfied"]; Sample Excel Data DataRow SatisfactionExtremelySatisfied 0 1 2 TRUE 3 TRUE When reading the test data using OLEDB the cells with TRUE hold no value but when the preceding cells have the value FALSE entered it correctly gets the values TRUE. Am I missing something?

    Read the article

  • How can I assign a DBNull in a better way?

    - by Mike
    Hi, I need to parse value from a datarow and assign it to another datarow.If the input is valid, then I need to parse it to double or else add a dbnull value to the output.I'm doing the following, is there a better way to do it? public double? GetVolume(object data) { string colValue = data == null ? string.Empty : data.ToString(); double volume; if (!Double.TryParse(colValue.ToString(), out volume)) { return null; } return volume; } public void Assign(DataRow theRowInput,DataRow theRowOutput) { double? volume = GetVolume(theRowInput[0]); if(volumne.HasValue) theRowOutput[0] = volume.value; else theRowOutput[0] = DbNull.Value; return theRowOutput; } Thanks, -M

    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

  • Bridge or Factory and How

    - by Chris
    I'm trying to learn patterns and I've got a job that is screaming for a pattern, I just know it but I can't figure it out. I know the filter type is something that can be abstracted and possibly bridged. I'M NOT LOOKING FOR A CODE REWRITE JUST SUGGESTIONS. I'm not looking for someone to do my job. I would like to know how patterns could be applied to this example. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.IO; using System.Xml; using System.Text.RegularExpressions; namespace CopyTool { class CopyJob { public enum FilterType { TextFilter, RegExFilter, NoFilter } public FilterType JobFilterType { get; set; } private string _jobName; public string JobName { get { return _jobName; } set { _jobName = value; } } private int currentIndex; public int CurrentIndex { get { return currentIndex; } } private DataSet ds; public int MaxJobs { get { return ds.Tables["Job"].Rows.Count; } } private string _filter; public string Filter { get { return _filter; } set { _filter = value; } } private string _fromFolder; public string FromFolder { get { return _fromFolder; } set { if (Directory.Exists(value)) { _fromFolder = value; } else { throw new DirectoryNotFoundException(String.Format("Folder not found: {0}", value)); } } } private List<string> _toFolders; public List<string> ToFolders { get { return _toFolders; } } public CopyJob() { Initialize(); } private void Initialize() { if (ds == null) { ds = new DataSet(); } ds.ReadXml(Properties.Settings.Default.ConfigLocation); LoadValues(0); } public void Execute() { ExecuteJob(FromFolder, _toFolders, Filter, JobFilterType); } public void ExecuteAll() { string OrigPath; List<string> DestPaths; string FilterText; FilterType FilterWay; foreach (DataRow rw in ds.Tables["Job"].Rows) { OrigPath = rw["FromFolder"].ToString(); FilterText = rw["FilterText"].ToString(); switch (rw["FilterType"].ToString()) { case "TextFilter": FilterWay = FilterType.TextFilter; break; case "RegExFilter": FilterWay = FilterType.RegExFilter; break; default: FilterWay = FilterType.NoFilter; break; } DestPaths = new List<string>(); foreach (DataRow crw in rw.GetChildRows("Job_ToFolder")) { DestPaths.Add(crw["FolderPath"].ToString()); } ExecuteJob(OrigPath, DestPaths, FilterText, FilterWay); } } private void ExecuteJob(string OrigPath, List<string> DestPaths, string FilterText, FilterType FilterWay) { FileInfo[] files; switch (FilterWay) { case FilterType.RegExFilter: files = GetFilesByRegEx(new Regex(FilterText), OrigPath); break; case FilterType.TextFilter: files = GetFilesByFilter(FilterText, OrigPath); break; default: files = new DirectoryInfo(OrigPath).GetFiles(); break; } foreach (string fld in DestPaths) { CopyFiles(files, fld); } } public void MoveToJob(int RecordNumber) { Save(); LoadValues(RecordNumber - 1); } public void AddToFolder(string folderPath) { if (Directory.Exists(folderPath)) { _toFolders.Add(folderPath); } else { throw new DirectoryNotFoundException(String.Format("Folder not found: {0}", folderPath)); } } public void DeleteToFolder(int index) { _toFolders.RemoveAt(index); } public void Save() { DataRow rw = ds.Tables["Job"].Rows[currentIndex]; rw["JobName"] = _jobName; rw["FromFolder"] = _fromFolder; rw["FilterText"] = _filter; switch (JobFilterType) { case FilterType.RegExFilter: rw["FilterType"] = "RegExFilter"; break; case FilterType.TextFilter: rw["FilterType"] = "TextFilter"; break; default: rw["FilterType"] = "NoFilter"; break; } DataRow[] ToFolderRows = ds.Tables["Job"].Rows[currentIndex].GetChildRows("Job_ToFolder"); for (int i = 0; i <= ToFolderRows.GetUpperBound(0); i++) { ToFolderRows[i].Delete(); } foreach (string fld in _toFolders) { DataRow ToFolderRow = ds.Tables["ToFolder"].NewRow(); ToFolderRow["JobId"] = ds.Tables["Job"].Rows[currentIndex]["JobId"]; ToFolderRow["Job_Id"] = ds.Tables["Job"].Rows[currentIndex]["Job_Id"]; ToFolderRow["FolderPath"] = fld; ds.Tables["ToFolder"].Rows.Add(ToFolderRow); } } public void Delete() { ds.Tables["Job"].Rows.RemoveAt(currentIndex); LoadValues(currentIndex++); } public void MoveNext() { Save(); currentIndex++; LoadValues(currentIndex); } public void MovePrevious() { Save(); currentIndex--; LoadValues(currentIndex); } public void MoveFirst() { Save(); LoadValues(0); } public void MoveLast() { Save(); LoadValues(ds.Tables["Job"].Rows.Count - 1); } public void CreateNew() { Save(); int MaxJobId = 0; Int32.TryParse(ds.Tables["Job"].Compute("Max(JobId)", "").ToString(), out MaxJobId); DataRow rw = ds.Tables["Job"].NewRow(); rw["JobId"] = MaxJobId + 1; ds.Tables["Job"].Rows.Add(rw); LoadValues(ds.Tables["Job"].Rows.IndexOf(rw)); } public void Commit() { Save(); ds.WriteXml(Properties.Settings.Default.ConfigLocation); } private void LoadValues(int index) { if (index > ds.Tables["Job"].Rows.Count - 1) { currentIndex = ds.Tables["Job"].Rows.Count - 1; } else if (index < 0) { currentIndex = 0; } else { currentIndex = index; } DataRow rw = ds.Tables["Job"].Rows[currentIndex]; _jobName = rw["JobName"].ToString(); _fromFolder = rw["FromFolder"].ToString(); _filter = rw["FilterText"].ToString(); switch (rw["FilterType"].ToString()) { case "TextFilter": JobFilterType = FilterType.TextFilter; break; case "RegExFilter": JobFilterType = FilterType.RegExFilter; break; default: JobFilterType = FilterType.NoFilter; break; } if (_toFolders == null) _toFolders = new List<string>(); _toFolders.Clear(); foreach (DataRow crw in rw.GetChildRows("Job_ToFolder")) { AddToFolder(crw["FolderPath"].ToString()); } } private static FileInfo[] GetFilesByRegEx(Regex rgx, string locPath) { DirectoryInfo d = new DirectoryInfo(locPath); FileInfo[] fullFileList = d.GetFiles(); List<FileInfo> filteredList = new List<FileInfo>(); foreach (FileInfo fi in fullFileList) { if (rgx.IsMatch(fi.Name)) { filteredList.Add(fi); } } return filteredList.ToArray(); } private static FileInfo[] GetFilesByFilter(string filter, string locPath) { DirectoryInfo d = new DirectoryInfo(locPath); FileInfo[] fi = d.GetFiles(filter); return fi; } private void CopyFiles(FileInfo[] files, string destPath) { foreach (FileInfo fi in files) { bool success = false; int i = 0; string copyToName = fi.Name; string copyToExt = fi.Extension; string copyToNameWithoutExt = Path.GetFileNameWithoutExtension(fi.FullName); while (!success && i < 100) { i++; try { if (File.Exists(Path.Combine(destPath, copyToName))) throw new CopyFileExistsException(); File.Copy(fi.FullName, Path.Combine(destPath, copyToName)); success = true; } catch (CopyFileExistsException ex) { copyToName = String.Format("{0} ({1}){2}", copyToNameWithoutExt, i, copyToExt); } } } } } public class CopyFileExistsException : Exception { public string Message; } }

    Read the article

  • PHPExcel reading columns

    - by user1270150
    I am new to using the PHPExcel and am struggling to implement a basic reader that can be used to read only specified columns, with all rows from a spreadsheet into an array, which I would like to present in a webpage. After reading the supplied documentation and examples, I am struggling to wrap my head round the implementation of a number of examples, so any help would be much appreciated. I am using the following code to get the contents of the default worksheet into an array: for ($row = 2; $row <= $highestRow; $row++) { $dataRow = $objWorksheet->rangeToArray('A'.$row.':'.$highestColumn.$row,null, true, true, true); if ((isset($dataRow[$row]['A'])) && ($dataRow[$row]['A'] > '')) { ++$r; foreach($headingsArray as $columnKey => $columnHeading) { $columnHeading = rtrim($columnHeading); $columnHeading = preg_replace('/\s+/', ' ',$columnHeading); $columnHeading = preg_replace('/\ /', '_',$columnHeading); $columnHeading = strtolower($columnHeading); $namedDataArray[$r][$columnHeading] = $dataRow[$row][$columnKey]; } } } Above code reads through all the columns and rows and builds and array, but I would like to be able to add a configuration array that will declare columns that should be read...sure this is possible, so any help would be much appreciated. Thanks

    Read the article

  • Call method immediately after object construction in LINQ query

    - by Steffen
    I've got some objects which implement this interface: public interface IRow { void Fill(DataRow dr); } Usually when I select something out of db, I go: public IEnumerable<IRow> SelectSomeRows { DataTable table = GetTableFromDatabase(); foreach (DataRow dr in table.Rows) { IRow row = new MySQLRow(); // Disregard the MySQLRow type, it's not important row.Fill(dr); yield return row; } } Now with .Net 4, I'd like to use AsParallel, and thus LINQ. I've done some testing on it, and it speeds up things alot (IRow.Fill uses Reflection, so it's hard on the CPU) Anyway my problem is, how do I go about creating a LINQ query, which calls Fills as part of the query, so it's properly parallelized? For testing performance I created a constructor which took the DataRow as argument, however I'd really love to avoid this if somehow possible. With the constructor in place, it's obviously simple enough: public IEnumerable<IRow> SelectSomeRowsParallel { DataTable table = GetTableFromDatabase(); return from DataRow dr in table.Rows.AsParallel() select new MySQLRow(dr); } However like I said, I'd really love to be able to just stuff my Fill method into the LINQ query, and thus not need the constructor overload.

    Read the article

  • Strange behaviour of DataTable with DataGridView

    - by Paul
    Please explain me what is happening. I have created a WinForms .NET application which has DataGridView on a form and should update database when DataGridView inline editing is used. Form has SqlDataAdapter _da with four SqlCommands bound to it. DataGridView is bound directly to DataTable _names. Such a CellValueChanged handler: private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) { _da.Update(_names); } does not update database state although _names DataTable is updated. All the rows of _names have RowState == DataRowState.Unchanged Ok, I modified the handler: private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) { DataRow row = _names.Rows[e.RowIndex]; row.BeginEdit(); row.EndEdit(); _da.Update(_names); } this variant really writes modified cell to database, but when I attempt to insert new row into grid, I get an error about an absence of row with index e.RowIndex So, I decided to improve the handler further: private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) { if (_names.Rows.Count<e.RowIndex) { DataRow row = _names.Rows[e.RowIndex]; row.BeginEdit(); row.EndEdit(); } else { DataRow row = _names.NewRow(); row["NameText"] = dataGridView1["NameText", e.RowIndex].Value; _names.Rows.Add(row); } _da.Update(_names); } Now the really strange things happen when I insert new row to grid: the grid remains what it was until _names.Rows.Add(row); After this line THREE rows are inserted into table - two rows with the same value and one with Null value. The slightly modified code: DataRow row = _names.NewRow(); row["NameText"] = "--------------" _names.Rows.Add(row); inserts three rows with three different values: one as entered into the grid, the second with "--------------" value and third - with Null value. I really got stuck in guessing what is happening.

    Read the article

  • WPF DataGrid default column types

    - by Trindaz
    Hi, I'm using a DataGrid to display 2 possible types of DataRow in a DataTable. One type has the column Parent = NULL and the other has Parent set to another DataRow in the same DataTable. The list of column in the DataTable is always different, so explicitly describing each column is not possible. I want to display a UserControl in every cell of the Parent = DataRow rows, and default Text / Check boxes for the Parent = NULL rows. My first strategy is to try and set the default Column type for all automatically generated columns to be a DataGridTemplateColumn, regardless of datatype, so that I can use styles to then use either my UserControl or CheckBox or TextBox where required. How can I do this? More importantly, though, is there a better strategy than this? Cheers, Dave

    Read the article

  • C# winforms: DataSet with multiple levels of related tables

    - by Jake
    Hi, I am trying to use DataSet and DataAdapter to "filter" and "navigate" DataRows in DataTables. THE SITUATION: I have multiple logical objects, e.g. Car, Door and Hinge. I am loading a Form which will display complete Car information including each Door and their respective Hinges. In this senario, The form should display info for 1 car, 4 doors and 2 hinges for each door. Is it possible to use a SINGLE DataSet to navigate this Data? i.e. 1 DataRow in car_table, 4 DataRow in door_table and 8 DataRow in hinge_table, and still be able to navigate correctly between the different object and their relations? AND, able to DataAdapter.Update() easily? I have read about DataRelation but don't really understand how to use it. Not sure if it is the correct direction for my problem. Appreciate any advise. Thanks!

    Read the article

  • How to insert bulk data into mysql table from asp.net at once.

    - by kranthi
    Hi, I have a requirement that I need to read an excel sheet using asp.net/C# and insert all the records into mysql table.The excel sheet consists of around 2000 rows and 50 columns. Currently,upon reading the excel records ,I am inserting the records one by one using a prepare statement into mysql table.But its taking around 70 secs to do so because of the huge data. I've also thought of creating a new datarow, assigning values to each cell,adding the resulting datarow to datatable and finally calling dataadapter.update(...).But it seems to be complex because I got around 50 columns and hence I'll have to assign 50 values to the datarow. Could someone please suggest if there is an alternate to improve the performance of the insertion? Thanks

    Read the article

  • Howto write a class where a property can be accessed without naming it.

    - by SchlaWiener
    I have a (dump) question regarding VB/C# I often use third party classes where I can access a child object with only specifying the id or key. Example: Instead of writing: DataRow row = GetAPopulatedDataRowSomeWhere(); Object result = row.Items[1]; // DataRow has no Items property Object result = row.Items["colName"]; // Also not possible I use this code to access the members: DataRow row = GetAPopulatedDataRowSomeWhere(); Object result = row[1]; Object result = row["colName"]; Can someone tell me how a class has to look like to support this syntax? My own class has a Dictionary that I want to access this way. MyClass["key"]; // <- that's what I want MyClass.SubItems["key"]; // <- that's how I use it now

    Read the article

  • Why does var evaluate to System.Object in "foreach (var row in table.Rows)"?

    - by DanM
    When I enter this foreach statement... foreach (var row in table.Rows) ...the tooltip for var says class System.Object I'm confused why it's not class System.Data.DataRow. (In case you're wondering, yes, I have using System.Data at the top of my code file.) If I declare the type explicitly, as in... foreach (DataRow row in table.Rows) ...it works fine with no errors. Also if I do... var numbers = new int[] { 1, 2, 3 }; foreach (var number in numbers) ...var evaluates to struct System.Int32. So, the problem is not that var doesn't work in a foreach clause. So, there's something strange about DataRowCollection where the items don't automatically evaluate to DataRow. But I can't figure out what it is. Does anyone have an explanation?

    Read the article

  • dataset - set parent child relations

    - by Night Walker
    Hello all I am trying to set the relations of rows in DataSet and then to show that relation in XTraaTreeList as tree with relations. | --| ----| but i get | | | I am doing this code but i get a view without any relations i get them all in one level. Any idea what i am doing wrong ? this.treeList1.BeginUpdate(); this.dataTable1.Clear(); DataRow dr = this.dataTable1.NewRow(); dr[0] = "father"; dr[1] = true; dr[2] = "ddd"; this.dataTable1.Rows.Add(dr); DataRow dr1 = this.dataTable1.NewRow(); dr1[0] = "son"; dr1[1] = true; dr1[2] = "ddd"; dr1.SetParentRow(dr); this.dataTable1.Rows.Add(dr1); DataRow dr2 = this.dataTable1.NewRow(); this.dataTable1.ParentRelations() dr2[0] = "grand son"; dr2[1] = true; dr2[2] = "ddd"; dr2.SetParentRow(dr1); this.dataTable1.Rows.Add(dr2); this.treeList1.EndUpdate();

    Read the article

  • search dataset from xml file

    - by Anelim
    Hi, I need to filter the results I obtain when I load my xml file. For example I need to search the xml data for items with keyword "Chemistry" for example. The below xml example is a summary of my xml file. The data is loaded in a gridview. Could you help? Thanks! Xml File (summary): <CONTRACTS> <CONTRACT> <CONTRACTID>779</CONTRACTID> <NAME>ContractName</NAME> <KEYWORDS>Chemistry, Engineering, Chemical</KEYWORDS> <CONTRACTSTARTDATE>1/8/2005</CONTRACTSTARTDATE> <CONTRACTENDDATE>31/7/2008</CONTRACTENDDATE> <COMMODITIES><COMMODITY><COMMODITYCODE>CHEM</COMMODITYCODE> <COMMODITYNAME>Chemicals</COMMODITYNAME></COMMODITY></COMMODITIES> </CONTRACT></CONTRACTS> My code behind code is: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim ds As DataSet = New DataSet() ds.ReadXml(AppDomain.CurrentDomain.BaseDirectory + "/testxml.xml") Dim dtContract As DataTable = ds.Tables(0) Dim dtJoinCommodities As DataTable = ds.Tables(1) Dim dtCommodity As DataTable = ds.Tables(2) dtContract.Columns.Add("COMMODITYCODE") dtContract.Columns.Add("COMMODITYNAME") Dim count As Integer = 0 Dim commodityCode As String = Nothing Dim commodityName As String = Nothing Dim dRowJoinCommodity As DataRow Dim trimChar As Char() = {","c, " "c} Dim textboxstring As String = "KEYWORDS like 'pencil'" For Each dRow As DataRow In dtContract.Select(textboxstring) commodityCode = "" commodityName = "" count = dtContract.Rows.IndexOf(dRow) dRowJoinCommodity = dtJoinCommodities.Rows(count) For Each dRowCommodities As DataRow In dtCommodity.Rows If dRowCommodities("COMMODITIES_Id").ToString() = dRowJoinCommodity("COMMODITIES_ID").ToString() Then commodityCode = commodityCode + dRowCommodities("COMMODITYCODE").ToString() + ", " commodityName = commodityName + dRowCommodities("COMMODITYNAME").ToString() + ", " End If Next commodityCode = commodityCode.TrimEnd(trimChar) commodityName = commodityName.TrimEnd(trimChar) dRow("COMMODITYCODE") = commodityCode dRow("COMMODITYNAME") = commodityName Next GridView1.DataSource = dtContract GridView1.DataBind() End Sub

    Read the article

  • Delete Duplicate records from large csv file C# .Net

    - by Sandhurst
    I have created a solution which read a large csv file currently 20-30 mb in size, I have tried to delete the duplicate rows based on certain column values that the user chooses at run time using the usual technique of finding duplicate rows but its so slow that it seems the program is not working at all. What other technique can be applied to remove duplicate records from a csv file Here's the code, definitely I am doing something wrong DataTable dtCSV = ReadCsv(file, columns); //columns is a list of string List column DataTable dt=RemoveDuplicateRecords(dtCSV, columns); private DataTable RemoveDuplicateRecords(DataTable dtCSV, List<string> columns) { DataView dv = dtCSV.DefaultView; string RowFilter=string.Empty; if(dt==null) dt = dv.ToTable().Clone(); DataRow row = dtCSV.Rows[0]; foreach (DataRow row in dtCSV.Rows) { try { RowFilter = string.Empty; foreach (string column in columns) { string col = column; RowFilter += "[" + col + "]" + "='" + row[col].ToString().Replace("'","''") + "' and "; } RowFilter = RowFilter.Substring(0, RowFilter.Length - 4); dv.RowFilter = RowFilter; DataRow dr = dt.NewRow(); bool result = RowExists(dt, RowFilter); if (!result) { dr.ItemArray = dv.ToTable().Rows[0].ItemArray; dt.Rows.Add(dr); } } catch (Exception ex) { } } return dt; }

    Read the article

  • Strange(?) Opera Floating

    - by SkaveRat
    I have some strange floating behaviour on opera (IE f's up completely different, but that's for later). I'm floating the i-icons to the right. It works nicely on Fx and WebKit, but opera shifts the icons down a bit. Anyone got an idea how this happenes? CSS: .dataRow { margin: 5px 0; clear:right; } .dataRow label{ display: block; float:left; width: 160px; vertical-align: middle; font-size: 80%; } .dataGroup a img { border:0;float:right; position:relative; right:0; } .dataGroup a:hover { background:#EBEDC7; text-decoration:none; } .dataGroup a.tooltip span { display:none; padding:2px 3px; margin-top:20px; width:100px; font-size: 80%; } .dataGroup a.tooltip:hover span { display:inline; position:absolute; border:1px solid #632D11; background:#C2BD6C; color:#fff; } HTML: <fieldset class="dataGroup"> <div class="dataRow"><label>Foobar:</label> <input name="foobar" size="10" value="somedata" /> <a href="#" class="tooltip"><img src="/img/admin/information.png"/><span>Tooltip Info</span></a></div> </fieldset>

    Read the article

  • jQuery Reference First Column in HTML Table

    - by Vic
    I have a table where all of the cells are INPUT tags. I have a function which looks for the first input cell and replaces it with it's value. So this: <tr id="row_0" class="datarow"> <td><input class="tabcell" value="Injuries"></td> <td><input class="tabcell" value="01"></td> becomes this: <tr id="row_0" class="datarow"> <td>Injuries</td> <td><input class="tabcell" value="01"></td> Here is the first part of the function: function setRowLabels() { var row = []; $('.dataRow').each(function(i) { row.push($('td input:eq(0)', this).val() + ' - '); $('td input:eq(0)', this).replaceWith($('td input:eq(0)', this).val()); $('td input:gt(0)', this).each(function(e) { etcetera But when the page reloads, the first column is not an input type, so it changes the second column to text too! Can I tell it to only change the first column, no matter what the type is? I tried $('td:eq(0)', this).replaceWith($('td:eq(0)', this).val()); but it does not work. Any suggestions appreciated! Thanks

    Read the article

  • System.Threading.Timer won't trigger

    - by mijatovic
    Hello guys, I am new here... I have one question, if somebody can help me. It is about timers (System.Threading.Timer). I want to break inevitable recursion: I have two columns in datarow and they are mutually dependant (price_without_VAT and price_with_VAT). Setting one of them will definitely cause StackOverflowException. So here's the idea: bool flag = true; void Reset(object state) { flag = true; } Now, wrap the method for changing value of one of the columns: { if(flag) { flag = false; System.Threading.Timer tmr = new System.Threading.Timer(new System.Threading.TimerCallback(Reset), null, 10, System.Threading.Timeout.Infinite); datarow.other_column = value; } } datarow.other_column.value line will immediately trigger the above method, but there will be no recursion because flag is false. In 10 ms flag should be back to true, and everything is back to normal. Now, when i follow the code in DEBUGGER, everything works fine, but when I start app NORMALLY Reset function simply will not trigger, flag is stuck to false forever and everything false apart. I play around with due_time parameter but nothing seems to help. Any ideas?

    Read the article

  • How can I bind events to strongly typed datasets of different types?

    My application contains several forms which consist of a strongly typed datagridview, a strongly typed bindingsource, and a strongly typed table adapter. I am using some code in each form to update the database whenever the user leaves the current row, shifts focus away from the datagrid or the form, or closes the form. This code is the same in each case, so I want to make a subclass of form, from which all of these forms can inherit. But the strongly typed data objects all inherit from component, which doesn't expose the events I want to bind to or the methods I want to invoke. The only way I can see of gaining access to the events is to use: Type(string Name).GetEvent(string EventName).AddEventHandler(object Target,Delegate Handler) Similarly, I want to call the Update method of the strongly typed table adapter, and am using Type(string Name).GetMethod(String name, Type[] params).Invoke(object target, object[] params). It works ok, but it seems very heavy handed. Is there a better way? Here is my code for the main class: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; using System.ComponentModel; namespace MyApplication { public class AutoSaveDataGridForm: Form { private DataRow PreviousRow; public Component Adapter { private get; set; } private Component dataGridView; public Component DataGridView { private get { return dataGridView; } set { dataGridView = value; Type t = dataGridView.GetType(); t.GetEvent("Leave").AddEventHandler(dataGridView, new EventHandler(DataGridView_Leave)); } } private Component bindingSource; public Component BindingSource { private get { return bindingSource; } set { bindingSource = value; Type t = bindingSource.GetType(); t.GetEvent("PositionChanged").AddEventHandler(bindingSource, new EventHandler(BindingSource_PositionChanged)); } } protected void Save() { if (PreviousRow != null && PreviousRow.RowState != DataRowState.Unchanged) { Type t = Adapter.GetType(); t.GetMethod("Update", new Type[] { typeof(DataRow[]) }).Invoke(Adapter, new object[] { new DataRow[] { PreviousRow } }); } } private void BindingSource_PositionChanged(object sender, EventArgs e) { BindingSource bindingSource = sender as BindingSource; DataRowView CurrentRowView = bindingSource.Current as DataRowView; DataRow CurrentRow = CurrentRowView.Row; if (PreviousRow != null && PreviousRow != CurrentRow) { Save(); } PreviousRow = CurrentRow; } private void InitializeComponent() { this.SuspendLayout(); // // AutoSaveDataGridForm // this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.AutoSaveDataGridForm_FormClosed); this.Leave += new System.EventHandler(this.AutoSaveDataGridForm_Leave); this.ResumeLayout(false); } private void DataGridView_Leave(object sender, EventArgs e) { Save(); } private void AutoSaveDataGridForm_FormClosed(object sender, FormClosedEventArgs e) { Save(); } private void AutoSaveDataGridForm_Leave(object sender, EventArgs e) { Save(); } } } And here is a (partial) form which implements it: public partial class FileTypesInherited :AutoSaveDataGridForm { public FileTypesInherited() { InitializeComponent(); } private void FileTypesInherited_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'sharedFoldersInformationV2DataSet.tblFileTypes' table. You can move, or remove it, as needed. this.tblFileTypesTableAdapter.Fill(this.sharedFoldersInformationV2DataSet.tblFileTypes); this.BindingSource = tblFileTypesBindingSource; this.Adapter = tblFileTypesTableAdapter; this.DataGridView = tblFileTypesDataGridView; } }

    Read the article

  • How to convert a DataSet object into an ObjectContext (Entity Framework) object on the fly?

    - by Marcel
    Hi all, I have an existing SQL Server database, where I store data from large specific log files (often 100 MB and more), one per database. After some analysis, the database is deleted again. From the database, I have created both a Entity Framework Model and a DataSet Model via the Visual Studio designers. The DataSet is only for bulk importing data with SqlBulkCopy, after a quite complicated parsing process. All queries are then done using the Entity Framework Model, whose CreateQuery Method is exposed via an interface like this public IQueryable<TTarget> GetResults<TTarget>() where TTarget : EntityObject, new() { return this.Context.CreateQuery<TTarget>(typeof(TTarget).Name); } Now, sometimes my files are very small and in such a case I would like to omit the import into the database, but just have a an in-memory representation of the data, accessible as Entities. The idea is to create the DataSet, but instead of bulk importing, to directly transfer it into an ObjectContext which is accessible via the interface. Does this make sense? Now here's what I have done for this conversion so far: I traverse all tables in the DataSet, convert the single rows into entities of the corresponding type and add them to instantiated object of my typed Entity context class, like so MyEntities context = new MyEntities(); //create new in-memory context ///.... //get the item in the navigations table MyDataSet.NavigationResultRow dataRow = ds.NavigationResult.First(); //here, a foreach would be necessary in a true-world scenario NavigationResult entity = new NavigationResult { Direction = dataRow.Direction, ///... NavigationResultID = dataRow.NavigationResultID }; //convert to entities context.AddToNavigationResult(entity); //add to entities ///.... A very tedious work, as I would need to create a converter for each of my entity type and iterate over each table in the DataSet I have. Beware, if I ever change my database model.... Also, I have found out, that I can only instantiate MyEntities, if I provide a valid connection string to a SQL Server database. Since I do not want to actually write to my fully fledged database each time, this hinders my intentions. I intend to have only some in-memory proxy database. Can I do simpler? Is there some automated way of doing such a conversion, like generating an ObjectContext out of a DataSet object? P.S: I have seen a few questions about unit testing that seem somewhat related, but not quite exact.

    Read the article

  • How can we copy the column data of one datatable to another,even if there is different column names

    - by Harikrishna
    I have two datatables. First is DataTable NameAdressPhones = new DataTable(); with Three columns Name,Adress and PhoneNo.But I want only two columns Name and Adress data so I am copy those columns (with data) to the new datatable DataTable NameAdress = new DataTable(); For that I do foreach (DataRow sourcerow in NameAdressPhones.Rows) { DataRow destRow = NameAdress.NewRow(); foreach (string colname in columns) { destRow[colname] = sourcerow[colname]; } NameAdress.Rows.Add(destRow); } Now I clear every time the NameAdressPhones(first) datatable when there are new records in the table.And every time there will be same no of columns but column name will be different like Nm instead of Name,Add instead of Address.Now problem is second datatable have already column names Name and Address and now I want to copy the columns data of Nm and Add to the second datatabel but the column names are different to the second datatable.So even If there is different column names I want to copy Nm column data of first datatable to the column Name of second datatable and column Add data of first datatable to column Address of second datatable.

    Read the article

  • C#: Object reference not set to an instance of an object.

    - by Vinzcent
    Hey, I get the following error: Object reference not set to an instance of an object This is my C Sharp code: DataTable tableAcces = dsAcces.Tables["dsPrinterAcces"]; DataTable tableMDF = dsAcces.Tables["dsPrinterMDF"]; DataRow newrow = null; foreach(DataRow dr in tableAcces.Rows) { newrow = tableMDF.NewRow(); newrow["PRINTER_ID"] = dr["PRINTER_ID"]; newrow["MERK"] = dr["MERK"]; newrow["MODEL"] = dr["MODEL"]; newrow["LOKAAL_ID"] = dr["LOKAAL_ID"]; tableMDF.Rows.Add(newrow); } daMDF.Update(dsMDF, "dsPrinterMDF"); lblSucces.Text = "Gelukt. De tabel printers is overgezet."; } In this line, he throws the error: newrow = tableMDF.NewRow(); Thanks a lot, Vincent

    Read the article

  • DataTable identity column not set after DataAdapter.Update/Refresh on table with "instead of"-trigge

    - by Arno
    Within our unit tests we use plain ADO.NET (DataTable, DataAdapter) for preparing the database resp. checking the results, while the tested components themselves run under NHibernate 2.1. .NET version is 3.5, SqlServer version is 2005. The database tables have identity columns as primary keys. Some tables apply instead-of-insert/update triggers (this is due to backward compatibility, nothing I can change). The triggers generally work like this: create trigger dbo.emp_insert on dbo.emp instead of insert as begin set nocount on insert into emp ... select @@identity end The insert statement issued by the ADO.NET DataAdapter (generated on-the-fly by a thin ADO.NET wrapper) tries to retrieve the identity value back into the DataRow: exec sp_executesql N' insert into emp (...) values (...); select id, ... from emp where id = @@identity ' But the DataRow's id-Column is still 0. When I remove the trigger temporarily, it works fine - the id-Column then holds the identity value set by the database. NHibernate on the other hand uses this kind of insert statement: exec sp_executesql N' insert into emp (...) values (...); select scope_identity() ' This works, the NHibernate POCO has its id property correctly set right after flushing. Which seems a little bit counter-intuitive to me, as I expected the trigger to run in a different scope, hence @@identity should be a better fit than scope_identity(). So I thought no problem, I will apply scope_identity() instead of @@identity under ADO.NET as well. But this has no effect, the DataRow value is still not updated accordingly. And now for the best part: When I copy and paste those two statements from SqlServer profiler into a Management Studio query (that is including "exec sp_executesql"), and run them there, the results seem to be inverse! There the ADO.NET version works, and the NHibernate version doesn't (select scope_identity() returns null). I tried several times to verify, but to no avail. Of course this just shows the resultset coming from the database, whatever happens inside NHibernate and ADO.NET is another topic. Also, several session properties defined by T-SQL SET are different in the two scenarios (Management Studio query vs. application at runtime) This is a real puzzle to me. I would be happy about any insights on that. Thank you!

    Read the article

  • What's a clean way to break up a DataTable into chunks of a fixed size with Linq?

    - by Michael Haren
    Update: Here's a similar question Suppose I have a DataTable with a few thousand DataRows in it. I'd like to break up the table into chunks of smaller rows for processing. I thought C#3's improved ability to work with data might help. This is the skeleton I have so far: DataTable Table = GetTonsOfData(); // Chunks should be any IEnumerable<Chunk> type var Chunks = ChunkifyTableIntoSmallerChunksSomehow; // ** help here! ** foreach(var Chunk in Chunks) { // Chunk should be any IEnumerable<DataRow> type ProcessChunk(Chunk); } Any suggestions on what should replace ChunkifyTableIntoSmallerChunksSomehow? I'm really interested in how someone would do this with access C#3 tools. If attempting to apply these tools is inappropriate, please explain! Update 3 (revised chunking as I really want tables, not ienumerables; going with an extension method--thanks Jacob): Final implementation: Extension method to handle the chunking: public static class HarenExtensions { public static IEnumerable<DataTable> Chunkify(this DataTable table, int chunkSize) { for (int i = 0; i < table.Rows.Count; i += chunkSize) { DataTable Chunk = table.Clone(); foreach (DataRow Row in table.Select().Skip(i).Take(chunkSize)) { Chunk.ImportRow(Row); } yield return Chunk; } } } Example consumer of that extension method, with sample output from an ad hoc test: class Program { static void Main(string[] args) { DataTable Table = GetTonsOfData(); foreach (DataTable Chunk in Table.Chunkify(100)) { Console.WriteLine("{0} - {1}", Chunk.Rows[0][0], Chunk.Rows[Chunk.Rows.Count - 1][0]); } Console.ReadLine(); } static DataTable GetTonsOfData() { DataTable Table = new DataTable(); Table.Columns.Add(new DataColumn()); for (int i = 0; i < 1000; i++) { DataRow Row = Table.NewRow(); Row[0] = i; Table.Rows.Add(Row); } return Table; } }

    Read the article

  • How can I delete from a GridView when DataSource is a DataTable?

    - by David
    My DataSource is a DataTable populated from file system data in Page_Load. There is no database. How can I remove rows from the DataTable and rebind? I thought this had to be done in the GridView_RowCommand "Delete" section... if(e.CommandName == "Delete") ... When I try to access the DataRow's within //get the datatable DataTable dt = this.gridCPCP.DataSource as DataTable; // Delete the record foreach (DataRow dr in dt.Rows) { .... dt is null. How do I reference the DataTable when deleting records?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >