Search Results

Search found 1168 results on 47 pages for 'datatable'.

Page 14/47 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • ADO.NET DataTable/DataRow Thread Safety

    - by Allen E. Scharfenberg
    Introduction A user reported to me this morning that he was having an issue with inconsistent results (namely, column values sometimes coming out null when they should not be) of some parallel execution code that we provide as part of an internal framework. This code has worked fine in the past and has not been tampered with lately, but it got me to thinking about the following snippet: Code Sample lock (ResultTable) { newRow = ResultTable.NewRow(); } newRow["Key"] = currentKey; foreach (KeyValuePair<string, object> output in outputs) { object resultValue = output.Value; newRow[output.Name] = resultValue != null ? resultValue : DBNull.Value; } lock (ResultTable) { ResultTable.Rows.Add(newRow); } (No guarantees that that compiles, hand-edited to mask proprietery information.) Explanation We have this cascading type of locking code other places in our system, and it works fine, but this is the first instance of cascading locking code that I have come across that interacts with ADO .NET. As we all know, members of framework objects are usually not thread safe (which is the case in this situation), but the cascading locking should ensure that we are not reading and writing to ResultTable.Rows concurrently. We are safe, right? Hypothesis Well, the cascading lock code does not ensure that we are not reading from or writing to ResultTable.Rows at the same time that we are assigning values to columns in the new row. What if ADO .NET uses some kind of buffer for assigning column values that is not thread safe--even when different object types are involved (DataTable vs. DataRow)? Has anyone run into anything like this before? I thought I would ask here at StackOverflow before beating my head against this for hours on end :) Conclusion Well, the consensus appears to be that changing the cascading lock to a full lock has resolved the issue. That is not the result that I expected, but the full lock version has not produced the issue after many, many, many tests. The lesson: be wary of cascading locks used on APIs that you do not control. Who knows what may be going on under the covers!

    Read the article

  • Populate an Object Model from a data dataTable(C#3.0)

    - by Newbie
    I have a situation I am getting data from some external sources and is populating into the datatable. The data looks like this DATE WEEK FACTOR 3/26/2010 1 RM_GLOBAL_EQUITY 3/26/2010 1 RM_GLOBAL_GROWTH 3/26/2010 2 RM_GLOBAL_VALUE 3/26/2010 2 RM_GLOBAL_SIZE 3/26/2010 2 RM_GLOBAL_MOMENTUM 3/26/2010 3 RM_GLOBAL_HIST_BETA I have a object model like this public class FactorReturn { public int WeekNo { get; set; } public DateTime WeekDate { get; set; } public Dictionary<string, decimal> FactorCollection { get; set; } } As can be seen that the Date field is always constant. And a single(means unique) week can have multiple FACTORS. i.e. For a date(3/26/2010), for Week No. 1, there are two FACTORS(RM_GLOBAL_EQUITY and RM_GLOBAL_GROWTH). Similarly, For a date(3/26/2010), for Week No. 2, there are three FACTORS(RM_GLOBAL_VALUE , RM_GLOBAL_SIZE and RM_GLOBAL_MOMENTUM ). Now we need to populate this data into our object model. The final output will be WeekDate: 3/26/2010 WeekNo : 1 FactorCollection : RM_GLOBAL_EQUITY FactorCollection : RM_GLOBAL_GROWTH WeekNo : 2 FactorCollection : RM_GLOBAL_VALUE FactorCollection : RM_GLOBAL_SIZE FactorCollection : RM_GLOBAL_MOMENTUM WeekNo : 3 FactorCollection : RM_GLOBAL_HIST_BETA That is, overall only 1 single collection, where the Factor type will vary depending on week numbers. I have tried but of useless. Nothing works. Could you please help me?. I feel it is very tough I am using C# 3.0 Thanks

    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

  • Bind Config section to DataTable using c#

    - by srk
    I have the following config section in my app.config file and the code to iterate through config section to retrieve the values. But i want to save the values of config section to a datatable in a proper structure. How ? I want to show all the values in datagridview with appropriate columns. <configSections> <section name="ServerInfo" type="System.Configuration.IConfigurationSectionHandler" /> </configSections> <ServerInfo> <Server id="1"> <Name>SRUAV1</Name> <key> 1 </key> <IP>10.1.150.110</IP> <Port>7901</Port> </Server> <Server id="2"> <Name>SRUAV2</Name> <key> 4 </key> <IP>10.1.150.110</IP> <Port>7902</Port> </Server> <Server id="3"> <Name>SRUAV3</Name> <key> 6 </key> <IP>10.1.150.110</IP> <Port>7904</Port> </Server> </ServerInfo> Code : public void GetServerValues(string strSelectedServer) { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ConfigurationSection section = config.GetSection("ServerInfo"); XmlDocument xml = new XmlDocument(); xml.LoadXml(section.SectionInformation.GetRawXml()); string temp = ""; XmlNodeList applicationList = xml.DocumentElement.SelectNodes("Server"); for (int i = 0; i < applicationList.Count; i++) { object objAppId = applicationList[i].Attributes["id"]; int iAppId = 0; if (objAppId != null) { iAppId = Convert.ToInt32(applicationList[i].Attributes["id"].Value); } temp = BuildServerValues(applicationList[i]); } } public string BuildServerValues(XmlNode applicationNode) { for (int i = 0; i < applicationNode.ChildNodes.Count; i++) { if (applicationNode.ChildNodes.Item(i).Name.ToString().Equals("Name")) { strServerName = applicationNode.ChildNodes.Item(i).InnerXml.ToString(); } if (applicationNode.ChildNodes.Item(i).Name.ToString().Equals("IP")) { strIP = applicationNode.ChildNodes.Item(i).InnerXml.ToString(); } if (applicationNode.ChildNodes.Item(i).Name.ToString().Equals("Port")) { strPort = applicationNode.ChildNodes.Item(i).InnerXml.ToString(); } } return strServerName; }

    Read the article

  • Binding search results to data grid

    - by Abid
    I want to add search functionality to my program. There's a class which has this function: public DataTable Search() { string SQL = "Select * from Customer where " + mField + " like '%" + mValue + "%'"; DataTable dt = new DataTable(); dt = dm.GetData(SQL); return (dt); } There are setter and getter properties for mField and mValue. DM is the object of class DataManagement, which has a method GetData: public DataTable GetData(string SQL) { SqlCommand command = new SqlCommand(); SqlDataAdapter dbAdapter = new SqlDataAdapter(); DataTable DataTable = new DataTable(); command.Connection = clsConnection.GetConnection(); command.CommandText = SQL; dbAdapter.SelectCommand = command; dbAdapter.Fill(DataTable); return (DataTable); } The search functionality is currently implemented like this: private void btnfind_Click(object sender, EventArgs e) { //cust is the object of class customer// if (tbCustName.Text != "") { cust.Field="CustName"; cust.Value = tbCustName.Text; } else if (tbAddress.Text != "") { cust.Value = tbAddress.Text; cust.Field="Address"; } else if (tbEmail.Text != "") { cust.Value = tbEmail.Text; cust.Field="Email"; } else if (tbCell.Text != "") { cust.Value = tbCell.Text; cust.Field = "Cell"; } DataTable dt = new DataTable(); dt = cust.Search(); dgCustomer.DataSource = dt; RefreshGrid(); } private void RefreshGrid() { DataTable dt = new DataTable(); dt = cust.GetCustomers(); dgCustomer.DataSource = dt; } This is not working. I don't know why. Please help.

    Read the article

  • please help me for performing serch in my program

    - by Abid
    i want to perform searching in my programe.. i have my class in which i have made a function i.e. public DataTable Search() { string SQL = "Select * from Customer where " + mField + " like '%" + mValue + "%'"; DataTable dt = new DataTable(); dt = dm.GetData(SQL); return (dt); } in which i have made setters and getters for mField and mValue.. where dm is the object of class Datamanagement in which i have made a function GetData i.e. public DataTable GetData(string SQL) { SqlCommand command = new SqlCommand(); SqlDataAdapter dbAdapter = new SqlDataAdapter(); DataTable DataTable = new DataTable(); command.Connection = clsConnection.GetConnection(); command.CommandText = SQL; dbAdapter.SelectCommand = command; dbAdapter.Fill(DataTable); return (DataTable); } and behind the search button, i have written.. private void btnfind_Click(object sender, EventArgs e) { //cust is the object of class customer// if (tbCustName.Text != "") { cust.Field="CustName"; cust.Value = tbCustName.Text; } else if (tbAddress.Text != "") { cust.Value = tbAddress.Text; cust.Field="Address"; } else if (tbEmail.Text != "") { cust.Value = tbEmail.Text; cust.Field="Email"; } else if (tbCell.Text != "") { cust.Value = tbCell.Text; cust.Field = "Cell"; } DataTable dt = new DataTable(); dt = cust.Search(); dgCustomer.DataSource = dt; RefreshGrid(); } where my referesh grid fuction does that : private void RefreshGrid() { DataTable dt = new DataTable(); dt = cust.GetCustomers(); dgCustomer.DataSource = dt; } but this is not working.. i dont knw y.. please help..

    Read the article

  • C# how to display datetimepicker control for all rows of gridview

    - by ronny
    Hi, In my application I am creating rows and columns dynamically. I created a column of type System.DateTime. After this i want to display datetimepicker control for all rows in that column. I created a column using dataTable.Columns.Add("CreatedOn", Type.GetType("System.DateTime")); and i am adding rows as foreach(String filename ......) dataTable_FileProperty.Rows.Add(filename,//here i want to add dateTimePicker So, what is a solution for this. EDIT: Please provide some code snippet. I am new to C#.net. Thanks.

    Read the article

  • How to "interleave" two DataTables.

    - by Brent
    Take these two lists: List 1 Red Green Blue List 2 Brown Red Blue Purple Orange I'm looking for a way to combine these lists together to produce: List 3 Brown Red Green Blue Purple Orange I think the basic rules are these: 1) Insert on top the list any row falling before the first common row (e.g., Brown comes before the first common row, Red); 2) Insert items between rows if both lists have two items (e.g., List 1 inserts Green between Red and Blue); and 3) Insert rows on the bottom if the there's no "between-ness" found in 2 (e.g., List 2 inserts Orange at the bottom). The lists are stored in a DataTable. I'm guessing I'll have to switch between them while iterating, but I'm having a hard time figuring out a method of combining the rows. Thanks for any help. --Brent

    Read the article

  • Error : while creating a file.

    - by Harikrishna
    I am storing records of datatable to csv file with the help of the following code : // we'll use these to check for rows with nulls var columns = yourTable.Columns .Cast<DataColumn>(); using (var writer = new StreamWriter(yourPath)) { for (int i = 0; i < yourTable.Rows.Count; i++) { DataRow row = yourTable.Rows[i]; // check for any null cells if (columns.Any(column => row.IsNull(column))) continue; string[] textCells = row.ItemArray .Select(cell => cell.ToString()) // may need to pick a text qualifier here .ToArray(); // check for non-null but EMPTY cells if (textCells.Any(text => string.IsNullOrEmpty(text))) continue; writer.WriteLine(string.Join(",", textCells)); } } But I get the error like System.UnauthorizedAccessException was unhandled Message="Access to the path 'D:\\Harikrishna\\Monthly Reports' is denied." What can be the problem and solution ?

    Read the article

  • Constant value.

    - by Harikrishna
    Is there any constant value like if we display it in the datagridview it will not display and if we add it in the decimal value the value remains as it is ? Like what I am doing is, I am making addition of two columns say B,C for the column A like dataTable.Columns["A"].Expression="B+C"; Now problem is when there is any value of column B or C is null then there is no value in the column A because of A=B+C like 1+null is null. And even I can not replace 0 where there is null for the column B or C because I am displaying records of each column A,B and C in the datagridview and I don't want to display value for column which has value null so if I replace 0 where there is null then 0 will be displayed for that column which I don't want. So what should I do for that ? So what is the constant value which I should replace for null value for the column B and C so if value of A remains it is and even that value will not be displayed in the datagridview.

    Read the article

  • JSF session issue

    - by user234194
    I have got a situation where I have list of records say 10,000, I am using datatable and I am using paging,(10 records per display). I wanted to put put that list in the session as: facesContext........put("mylist", mylist); And in the getters of the mylist, I have public List<MyClass> getMyList() { if(mylist== null){ mylist= (List<MyClass>) FacesContext......getSessionMap().get("mylist"); } return mylist; } Now the problem is whene ever i click on paging button to go to second page, only the first records are displayed, I know i am missing some thing, and I have few questions: Is the way of putting the list in session correct. Is this the way I should be calling the list in my case. Thnaks in advance...

    Read the article

  • C# = assigning custom objects to array with a for loop?

    - by John M
    Given this example: // Create an arary of car objects. car[] arrayOfCars= new car[] { new car("Ford",1992), new car("Fiat",1988), new car("Buick",1932), new car("Ford",1932), new car("Dodge",1999), new car("Honda",1977) }; I tried something like this: for (int i = 0; i < dtable.Rows.Count; i++) { DataRow drow = dtable.Rows[i]; arrayOfCars[] = new car(drow["make"].ToString(), drow["year"].ToString()); } How do I add additional data to the array while looping through a datatable?

    Read the article

  • C# Same DataSource + Multiple DataGridViews = Data Binding Issues?

    - by C. Griffin
    Here's what I'm doing: I have (2) DataGridView controls DGV #1 is bound to the DataSet, DGV #2 is bound to a DataView of the SAME DataSet Now, what I'm needing to accomplish here is this: When a user checks a boolean column on the original DGV, the second DGV should now display the newly checked row also. The context is that the first DGV is a master list, and the second one is a "favorite" view of the first. When I check the rows, the favorite column does NOT update. Do I need to use a DataAdapter to actually update the database, or can I operate directly on the DataSet (DataTable) -- or even with the Rows in the original DataGridView?

    Read the article

  • How to Get a Specific Column Value from a DataTable? - C#.NET Winforms

    - by peace
    I have a datatable. I need to fetch a certain column value based on the user input. For example, lets say the datatable has two columns CountryID and CountryName. I need to find CountryID in the datatable based on the user input country name. I could just open a connection with DB and run the query select countryID from Country where countryName = @userinput. Is there anyway i could do this on the datatable. Thanks

    Read the article

  • How to Get a Specific Column Value from a DataTable?

    - by peace
    I have a datatable. I need to fetch a certain column value based on the user input. For example, lets say the datatable has two columns CountryID and CountryName. I need to find CountryID in the datatable based on the user input country name. I could just open a connection with DB and run the query select countryID from Country where countryName = @userinput. Is there anyway i could do this on the datatable.

    Read the article

  • How can I synchronise two datatables and update the target in the database?

    - by Craig
    I am trying to synchronise two tables between two databases. I thought that the best way to do this would be to use the DataTable.Merge method. This seems to pick up the changes, but nothing ever gets committed to the database. So far I have: string tableName = "[Table_1]"; string sql = "select * from " + tableName; using (SqlConnection sourceConn = new SqlConnection(ConfigurationManager.ConnectionStrings["source"].ConnectionString)) { SqlDataAdapter sourceAdapter = new SqlDataAdapter(); sourceAdapter.SelectCommand = new SqlCommand(sql, sourceConn); sourceConn.Open(); DataSet sourceDs = new DataSet(); sourceAdapter.Fill(sourceDs); using (SqlConnection targetConn = new SqlConnection(ConfigurationManager.ConnectionStrings["target"].ConnectionString)) { SqlDataAdapter targetAdapter = new SqlDataAdapter(); targetAdapter.SelectCommand = new SqlCommand(sql, targetConn); SqlCommandBuilder builder = new SqlCommandBuilder(targetAdapter); targetAdapter.InsertCommand = builder.GetInsertCommand(); targetAdapter.UpdateCommand = builder.GetUpdateCommand(); targetAdapter.DeleteCommand = builder.GetDeleteCommand(); targetConn.Open(); DataSet targetDs = new DataSet(); targetAdapter.Fill(targetDs); targetDs.Tables[0].TableName = tableName; sourceDs.Tables[0].TableName = tableName; targetDs.Tables[0].Merge(sourceDs.Tables[0]); targetAdapter.Update(targetDs.Tables[0]); } } At the present time, there is one row in the source that is not in the target. This row is never transferred. I have also tried it with an empty target, and nothing is transferred.

    Read the article

  • Class design when working with dataset

    - by MC
    If you have to retrieve data from a database and bring this dataset to the client, and then allow the user to manipulate the data in various ways before updating the database again, what is a good class design for this if the data tables will not have a 1:1 relationship with the class objects? Here are some I came up with: Just manipulate the DataSet itself on the client and then send it back to the database as is. This will work though obviously the code will be very dirty and not well-structured. Same as #1, but wrap the dataset code around classes. What I mean is that you may have a class that takes a dataset or a datatable in its constructor, and then provides public methods and properties to simplify the code. Inside these methods and properties it will be reading or manipulating the dataset. To update the database afterwards will be easy because you already have the updated dataset. Get rid of the dataset entirely on the client, convert to objects, then convert back to a dataset when needing to update the database. Is there any good resources where I can find information on this?

    Read the article

  • Populating and Using Dynamic Classes in C#/.NET 4.0

    - by Bob
    In our application we're considering using dynamically generated classes to hold a lot of our data. The reason for doing this is that we have customers with tables that have different structures. So you could have a customer table called "DOG" (just making this up) that contains the columns "DOGID", "DOGNAME", "DOGTYPE", etc. Customer #2 could have the same table "DOG" with the columns "DOGID", "DOG_FIRST_NAME", "DOG_LAST_NAME", "DOG_BREED", and so on. We can't create classes for these at compile time as the customer can change the table schema at any time. At the moment I have code that can generate a "DOG" class at run-time using reflection. What I'm trying to figure out is how to populate this class from a DataTable (or some other .NET mechanism) without extreme performance penalties. We have one table that contains ~20 columns and ~50k rows. Doing a foreach over all of the rows and columns to create the collection take about 1 minute, which is a little too long. Am I trying to come up with a solution that's too complex or am I on the right track? Has anyone else experienced a problem like this? Create dynamic classes was the solution that a developer at Microsoft proposed. If we can just populate this collection and use it efficiently I think it could work.

    Read the article

  • JQuery DataTables link item

    - by rogcg
    I'm trying to link the items from a specific column, but each one will be linked for a different id from the json string. Unfortunately I can't find a way to do this using the API (I know there is a lot of ways to do that without using the API ), but I'm looking for a way to link a item from a column (each one with a link for a specific id). So here is my code, I use getJSON to get the JSON from the server, and I load the data from this JSON to the table like this: $.getJSON("/method/from/server/", function(data) { var total = 0; $("#table_body").empty(); var oTable = $('#mytable').dataTable( { "sPaginationType" : "full_numbers", "aaSorting": [[ 0, "asc" ]] }); oTable.fnClearTable(); $.each(data, function(i, item) { oTable.fnAddData( [ item.contact_name, item.contact_email ] ); }); }); What I want to do, is for each row, link the contact_name to its id, which is also in the JSON, and can be accessed inside this $.each loop by using item.contact_id. Is there a way to do this using DataTables API, if yes, could you explain me and provide a good resource that will help me with this? Thanks.

    Read the article

  • DataTables - Total rowCount - How to cut euro sign in the columns?

    - by Ivan M
    For my DataTable I'm using the fnFooterCallback function to display the total amount of the column, which is working untill the columns contain a special character, like in this case a euro valuta sign. How can I adjust this code so it will not detect the euro sign? "fnFooterCallback": function ( nRow, aaData, iStart, iEnd, aiDisplay ) { /* * Calculate the total market share for all browsers in this table (ie inc. outside * the pagination) */ var iTotal = 0; for ( var i=0 ; i<aaData.length ; i++ ) { iTotal += aaData[i][7]*1; } /* Calculate the market share for browsers on this page */ var iPage = 0; for ( var i=iStart ; i<iEnd ; i++ ) { iPage += aaData[ aiDisplay[i] ][7]*1; } /* Modify the footer row to match what we want */ var nCells = nRow.getElementsByTagName('th'); nCells[1].innerHTML = parseInt(iPage); } Thank you in advance. EDIT With not detecting I mean to str_replace or something like that. Not familiar with javascript language..

    Read the article

  • Remove all rows in duplication (different from distinct row selection)

    - by user1671401
    How can I remove EVERY duplicating row in a DataTable, based on the value of two columns that are in duplication. Unfortunately, I am unable to find the equivalent LINQ Query. (I dont want distinct values even). The table below shall explain my problem I want to delete every row in duplication based on Column_A and Column_B COLUMN_A      COLUMN_B      COLUMN_C     COLUMN_D..... A                       B C                       D E                       F G                       H A                       B E                       F EXPECTED OUTPUT: COLUMN_A      COLUMN_B      COLUMN_C     COLUMN_D..... C                       D G                       H Please help

    Read the article

  • Inserting and Deleting Sub Rows in GridView

    - by Vincent Maverick Durano
    A user in the forums (http://forums.asp.net) is asking how to insert  sub rows in GridView and also add delete functionality for the inserted sub rows. In this post I'm going to demonstrate how to this in ASP.NET WebForms.  The basic idea to achieve this is we just need to insert row data in the DataSource that is being used in GridView since the GridView rows will be generated based on the DataSource data. To make it more clear then let's build up a sample application. To start fire up Visual Studio and create a WebSite or Web Application project and then add a new WebForm. In the WebForm ASPX page add this GridView markup below:   1: <asp:gridview ID="GridView1" runat="server" AutoGenerateColumns="false" onrowdatabound="GridView1_RowDataBound"> 2: <Columns> 3: <asp:BoundField DataField="RowNumber" HeaderText="Row Number" /> 4: <asp:TemplateField HeaderText="Header 1"> 5: <ItemTemplate> 6: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 7: </ItemTemplate> 8: </asp:TemplateField> 9: <asp:TemplateField HeaderText="Header 2"> 10: <ItemTemplate> 11: <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> 12: </ItemTemplate> 13: </asp:TemplateField> 14: <asp:TemplateField HeaderText="Header 3"> 15: <ItemTemplate> 16: <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox> 17: </ItemTemplate> 18: </asp:TemplateField> 19: <asp:TemplateField HeaderText="Action"> 20: <ItemTemplate> 21: <asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click" Text="Insert"></asp:LinkButton> 22: </ItemTemplate> 23: </asp:TemplateField> 24: </Columns> 25: </asp:gridview>   Then at the code behind source of ASPX page you can add this codes below:   1: private DataTable FillData() { 2:   3: DataTable dt = new DataTable(); 4: DataRow dr = null; 5:   6: //Create DataTable columns 7: dt.Columns.Add(new DataColumn("RowNumber", typeof(string))); 8:   9: //Create Row for each columns 10: dr = dt.NewRow(); 11: dr["RowNumber"] = 1; 12: dt.Rows.Add(dr); 13:   14: dr = dt.NewRow(); 15: dr["RowNumber"] = 2; 16: dt.Rows.Add(dr); 17:   18: dr = dt.NewRow(); 19: dr["RowNumber"] = 3; 20: dt.Rows.Add(dr); 21:   22: dr = dt.NewRow(); 23: dr["RowNumber"] = 4; 24: dt.Rows.Add(dr); 25:   26: dr = dt.NewRow(); 27: dr["RowNumber"] = 5; 28: dt.Rows.Add(dr); 29:   30: //Store the DataTable in ViewState for future reference 31: ViewState["CurrentTable"] = dt; 32:   33: return dt; 34:   35: } 36:   37: private void BindGridView(DataTable dtSource) { 38: GridView1.DataSource = dtSource; 39: GridView1.DataBind(); 40: } 41:   42: private DataRow InsertRow(DataTable dtSource, string value) { 43: DataRow dr = dtSource.NewRow(); 44: dr["RowNumber"] = value; 45: return dr; 46: } 47: //private DataRow DeleteRow(DataTable dtSource, 48:   49: protected void Page_Load(object sender, EventArgs e) { 50: if (!IsPostBack) { 51: BindGridView(FillData()); 52: } 53: } 54:   55: protected void LinkButton1_Click(object sender, EventArgs e) { 56: LinkButton lb = (LinkButton)sender; 57: GridViewRow row = (GridViewRow)lb.NamingContainer; 58: DataTable dtCurrentData = (DataTable)ViewState["CurrentTable"]; 59: if (lb.Text == "Insert") { 60: //Insert new row below the selected row 61: dtCurrentData.Rows.InsertAt(InsertRow(dtCurrentData, row.Cells[0].Text + "-sub"), row.RowIndex + 1); 62:   63: } 64: else { 65: //Delete selected sub row 66: dtCurrentData.Rows.RemoveAt(row.RowIndex); 67: } 68:   69: BindGridView(dtCurrentData); 70: ViewState["CurrentTable"] = dtCurrentData; 71: } 72:   73: protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { 74: if (e.Row.RowType == DataControlRowType.DataRow) { 75: if (e.Row.Cells[0].Text.Contains("-sub")) { 76: ((LinkButton)e.Row.FindControl("LinkButton1")).Text = "Delete"; 77: } 78: } 79: }   As you can see the code above is pretty straight forward and self explainatory but just to give you a short explaination the code above is composed of three (3) private methods which are the FillData(), BindGridView and InsertRow(). The FillData() method is a method that returns a DataTable and basically creates a dummy data in the DataTable to be used as the GridView DataSource. You can replace the code in that method if you want to use actual data from database but for the purpose of this example I just fill the DataTable with a dummy data on it. The BindGridVew is a method that handles the actual binding of GridVew. The InsertRow() is a method that returns a DataRow. This method handles the insertion of the sub row. Now in the LinkButton OnClick event, we casted the sender to a LinkButton to determine the specific object that fires up the event and get the row values. We then reference the Data from ViewState to get the current data that is being used in the GridView. If the LinkButton text is "Insert" then we will insert new row to the DataSource ( in this case the DataTable) based on the rowIndex if not then Delete the sub row that was added. Here are some screen shots of the output below: On initial load:   After inserting a sub row:   That's it! I hope someone find this post useful!   Technorati Tags: ASP.NET,C#,GridView

    Read the article

  • java.util.Map with HtmlDataTable

    - by gerry
    Hi, I'm developing an application on GlassFish v3 which uses Suns-RI of JavaEE6 and JSF2.0, etc. And the bad thing is, that no changes/switches away from Suns RI can be made (to use MyFaces or something like that). Now, the problem is, that I want to build HtmlDatatable by hand ( in Java code). The datatable should represent a java.util.Map where the first column should display the key and the second the values of the map. I've build successfully a PanelGrid from a java.util.List and used every time the "setExpressionValue" methods of UIComponent to bind the UI to the underlying List. But now, this doesn't work with the Map. Here is a snippet of my code: public HtmlDataTable getEntityDetailsDataTable() { ... Application app = FacesContext.getCurrentInstance().getApplication(); HtmlDataTable component = (HtmlDataTable)app.createComponent(HtmlDataTable.COMPONENT_TYPE); component.setValueExpression("value", ExpressionUtil.createValueExpression("#{entityTree.entity."+fieldName+".entrySet()}", Map.class)); component.setVar("param"); UIColumn column = new UIColumn(); UIOutput label1 = DynamicHtmlComponentCreator.createHtmlOutputText("#{param[key]}", String.class); column.getChildren().add(label1); UIOutput label2 = DynamicHtmlComponentCreator.createHtmlOutputText("#{param[value]}", String.class); column.getChildren().add(label2); component.getChildren().add(column); ... return component; } component.getChildren().add(column); ... return component; } So, further the problem is, that this code only prints out the content of the Map, on another page I need the values displayed in HtmlInputText elements and the whole map updated if the user clicks a i.e. "Save" button. So, further the problem is, that this code only prints out the content of the Map, on another page I need the values displayed in HtmlInputText elements and the whole map updated if the user clicks a i.e. "Save" button. If there is a workaround, to represent the Map as to Lists...please help me, because for this (map as 2 lists) I've no idea how the underlying map/database model can be updated again. Hopefully, someone can help me....

    Read the article

  • How to insert null value for numeric field of a datatable in c#?

    - by Pandiya Chendur
    Consider My dynamically generated datatable contains the following fileds Id,Name,Mob1,Mob2 If my datatable has this it get inserted successfully, Id Name Mob1 Mob2 1 acp 9994564564 9568848526 But when it is like this it gets failed saying, Id Name Mob1 Mob2 1 acp 9994564564 The given value of type String from the data source cannot be converted to type decimal of the specified target column. I generating my datatable by readingt a csv file, CSVReader reader = new CSVReader(CSVFile.PostedFile.InputStream); string[] headers = reader.GetCSVLine(); DataTable dt = new DataTable(); foreach (string strHeader in headers) { dt.Columns.Add(strHeader); } string[] data; while ((data = reader.GetCSVLine()) != null) { dt.Rows.Add(data); } Any suggestion how to insert null value for numeric field during BulkCopy in c#... EDIT: I tried this dt.Columns["Mob2"].AllowDBNull = true; but it doesn't seem to work...

    Read the article

  • C# (ADO.Net): Defining DateDiff for a calculated column in a datatable

    - by Nir
    I have the column DateTimeExpired, and I would like to create another column called "Expired" which will show "Yes" or "No" according to the expiration date - "Yes" if the date has already passed. I wrote this: DataColumn colExpirationDate = new DataColumn("DateTimeExpired", typeof(DateTime)); DataColumn colExpired = new DataColumn("Expired", typeof(string), "IIF(DateDiff(DateTimeExpired, date())>= 0,'No','Yes')"); But I get an exception "The expression contains undefined function call DateDiff()." (please note that I always want to get the row, no matter if it's expired or not) How do I set the column's text to the correct form? Thanks!

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >