Dynamically setting MaxLength property of a DataColumn with DataAdapter - datatable

I have a datatable that I'm filling with SqlDataAdapter.Fill(). Is there a way to dynamically assign the MaxLength property to each string datacolumn to the maximum allowed by that column in the database?

So I googled for a while and found that the DataAdapter has another method besides Fill which is: FillSchema(), which includes the database schema into the DataTable. Since all I wanted to bring was the MaxLength property what I did was load the schema into another table and loop through the columns assigning the value to each one.
Of course if you wanted to keep all the constraints in the database within your table, then you'd need no loop and just load the schema into the datatable.

PedroC88's answer worked. To clarify the code needed for any newbies. Just above my adapters fill method, I wrote the fillschema method. The (SchemaType)2 argument is required. There are 2 different schematypes (1 and 2) and 2 is recommended as it applies existing table mappings (though I have no idea what this means).
myAdapter.FillSchema(dataTable, (SchemaType)2);
myAdapter.Fill(dataTable);
In this code 'myAdapter' is the name of my adapter and 'dataTable' is the name of my data table.

Related

Visual Studio 2013 Dataset Designer refresh relations

I have an application with a dataset linked to an sql server database. I have updated some of the names or foreign keys and primary keys in the sql server. How do I make those changes translate to the data set. For example, I had a primary key called fk_temsempl_xxxxx. I changed it to fk_temsempl on the sql database. How do I get that change to show in the dataset designer in visual studio?
I have tried running custom tool by right clicking on the dataset and clicking run custom tool. That didnt work. I tried configuring the table adapter of one of the tables where a change occured, but the name of the relation didnt change.
You actually just right click the relation and choose Edit Relation... or double click on the line (when the mouse cursor changes from arrow to drag symbol) but I honestly wouldn't bother; you'll then have further refactoring to do in the code anywhere the relation is used, and it can be heavily used by visual designers.
You also get the problem that VS may not help you with the refactoring: in data binding scenarios most things that can be a source of data can also be a collection of multiple things that can be a valid DataSource. They then rely on a string DataMember to determine which of the collections of data in the data source should be used for the data.
For example, when a bindingsource is bound to list a DataTable, the bindingsource.DataSource property might be the DataSet object that contains the DataTable, and thebindingsource.DataMemberis a string of "YOUR_TABLE_NAME". the BindingSource might not be bound asmyBindignSource.DataSource = myDataSet.MyDataTable`. Refactoring inside strings involves a find and replace
DataRelations in a DataSet are created from foreign keys as they were discovered when the relevant table(s) were added to the dataset but it is important to note that, like DataTables and everything else, they are NOTHING to do with the database schema objects at all - they aren't permanently associated with them, the dataset entities are just set up looking something like the database objects when they (dataset entities) are first created. DataTables are created from only those columns selected, and whatever .NET datatypes closely resemble the types output by the query. For a table of:
Person
------
Name VARCHAR(50)
SSN INTEGER
Birthdate DATE
If you created the table with SELECT * FROM Person you'd get a datatable with Name (string), SSN (int), Birthdate (datetime) but if you made a new datatable in the dataset based on SELECT LEFT(Name, 1) as Initial, PADLEFT(SSN, 20) as PadSSN, DATEDIFF(day, Birthdate, NOW()) as AgeDays FROM Person then you'd get a datatable of Initial (string), PadSSN (string), AgeDays (int) - i.e. the datatable looks nothing like the db table. This concept of disconnection between dataset and db is pervasive, and really the only things that relate in any way to the database are the properties that specify which DB table/column a particular DataTable/DataColumn relates to for purposes of loading/saving data. Your Person.Name datacolumn can be renamed to Blahblah, but it will still have a .SourceColumn property that is set to "Name" - that's how the mapping between dataset and db works; dataset is predominantly completely independent of the db. Renaming a DB column would require a change to the SourceColumn property only
DataRelations don't even have this notion of linking to the parent relation in the database; there's no SourceRelation or SourceFK proeprty because there is no need to. They're set up with the same rules and a generated name all based on the rules of the FK, but then they function independently and only within the dataset. If you rename or even remove an FK from the db the dataset will carry on working in the same restricted way it always did; adding a datarow to a child table when no aprent row exists for it will throw an exception - none of it anything to do with the FK in the db, and the DataRelation can have different rules to the FK (e.g it can cascade deletes when the FK is NOACTION) or even different columns. You can have more or fewer DataRelations than the DB has FKs
Run Custom Tool is not a "contact the DB and see what changes have occurred there and replicate them into the dataset", it is a "turn the XSD that describes the dataset into a bunch of C# classes that implement strongly typed dataset/table/relation/column etc objects". Any time you change the XSD by making an edit in the visual designer and hit save, the custom tool is run. If you edit the XSD directly in a text editor you may need to run it manually to have your changes reflected in c# classes
Reconfiguring a tableadapter probably won't do anything to the relations either; its solely concerned with changing the datatable and tableadapter. If you really want to refresh the relations, delete the datatable from the set and recreate it. Be prepared for a potentially significant mop up/refactoring of code

Servicenow - Service Catalog Reference Field - Insert different column than the display value

Let me describe my problem:
I have a table for all my IT-Services. I reference to this table more than once, for different purposes. Most of the time I need to reference to the name of the service. That's why I keep the name as displayed value.
One Column of that table is a service_id (custom field) which is for example "Service_004". Now in a catalog request Item the User has to fill in the service_id in a reference field.
But since I have the name as displayed value, and I need it in other forms, I am unable to reference to the service_id.
Using the variable attributes field I managed to let the service be found using the autocomplete function. But in the reference field I still get the servicename. I know that I can change the display value in the dictionary, but this breaks other functions. So what I need is to change the display value just for one reference field.
Also I tried to create a new table called IT-Services2 with reference to my table IT-Services. Then I switched the display to true in the new table for my service_id, but this will even change it in the parent table.
Perhaps an onChange client script utilizing g_form.setLabelOf() ?
http://wiki.servicenow.com/index.php?title=GlideForm_(g_form)#setLabelOf
Maybe I'm not fully understanding your question...
I ran into this issue before, what you can do is create select box variable and use an on load client script to populate the list with the service_id(s) from the table you are referencing.
I would write a script include to pull the data from the table and call it from the client script via GlideAjax.

LINQ update statement using generic table and column names

OK, I've seen a lot of posts on creating generic LINQ statements, but these are usually based on select queries. What I need is a LINQ UPDATE statement that takes a generic parameter for the table to update and a generic parameter for the column to update.
The data model I'm working with has dozens of tables, and each table has potentially dozens of columns. What I'm really driving toward is a single Update statement that allows me to tell it at runtime which table and which column to update.
Dealing with data typing of these dynamically supplied fields will also be an issue since obviously I can't update a DateTime column with a decimal value for example.
So, can anyone point me at some code that shows a LINQ update process using generic parameters for table and column names.
Any help would be greatly appreciated!
You didn't specify Entity Framework with DbContext but if that is what you are using, this is pretty easy. The following code is written to work within the NerdDinner sample which can be downloaded from http://nerddinner.codeplex.com/
This code locates a dinner based on the id and sets the address property to "New Value"
Dinner dinner = db.Set<Dinner>().Find(id);
var entry = db.Entry(dinner);
entry.Property("Address").CurrentValue = "New Value";
db.SaveChanges();

Custom NSTableViewHeaderCell

I've created a custom NSTableViewHeaderCell class but I still have one issue with separators: How know if I am drawing the last column header or not?
Actualy I don't want to draw a separator for the last column but I didn't found a way to know it is the last one.
Thanks for your help
Since you're creating a subclass of NSTableHeaderCell, create one more property on it for a NSTableColumn. You can set this property as you create and set an instance of your subclass for each of your table's columns.
Now that your subclass instances know the table columns to which they belong, they can use this to determine the table view. From the table view, you can get an array of table columns, and if you compare a given table column to the lastObject value of that array, you should be able to tell if your header cell belongs to the last table column.
If you choose to enable reordering for your table columns, you may have some more coding to do, but this should get you started.
Good luck to you in your endeavors.

TableAdapter to return ONLY selected columns? (VS2008)

(VS2008) I'm trying to configure a TableAdapter in a Typed DataSet to return only a certain subset of columns from the main schema of the table on which it is based, but it always returns the entire schema (all columns) with blank values in the columns I have omitted.
The TableAdpater has the default Fill and GetData() methods that come from the wizard, which contain every column in the table, which is fine. I then added a new parameterized query method called GetActiveJobsByCustNo(CustNo), and I only included a few columns in the SQL query that I actually want to be in this table view.
But, again, it returns all the columns in the master table schema, with empty values for the columns I omitted.
The reason I am wanting this, is so I can just get a few columns back to use that table view with AutoGenerateColumns in an ASP.NET GridView. With it giving me back EVERY column i nthe schema, my presentation GridView contains way more columns that I want to show th user. And, I want to avoid have to declare the columns in the GridView.
When you add a new query to a given TableAdapter, it is going to assume the schema in which it is attached to, which is why you are getting blank values for the columns you don't want.
Since you mentioned having already created the procedure, what you need to do is use the Server Explorer to connect to the database and simply drag that stored procedure over into your XSD work area. What this will do is create a separate QueryAdapter that will have just the columns you specified (still strongly typed) and you can bind/interact with your GridView using that QueryAdapter instead.
Is the strongly typed dataset used in another query that returns all the rows from the table?
What you could do is create a dataview using the strongly typed dataset and expose a data table for your DataGridView.
I'm not sure what your requirements are totally, but this example should help you:
DataView dv = new DataView(ds.<Your_Table>);
// This will create a new data table with the same name,
// But with only two columns from the original table.
// This could then be bound to your data grid.
DataTable dt = dv.ToTable(false,
ds.<Your_Table>.<Your_Column1Column>.ColumnName,
ds.<Your_Table>.<Your_Column1Column>.ColumnName);
Just delete the columns you don't want at run-time before you bind to your Gridview. The underlying class is still just a DataTable after all.

Resources