I have a datatable on which I am applying Select() method. After that I want to get the result into an array of String. I have tried the following code but it is not working.
Please let me know the exact solutions for this.
DataTable dtget = HttpContext.Current.Cache["Hello"] as DataTable;
string sqlFilter = "Securityid = '" + CommonClass.Encryptdata(txtSecurity.Text) + "'";
DataRow[] dr = dtget.Select(sqlFilter);
if (dr.Length > 0)
{
String[] Con;
for (int i = 0; i <= dr.Length; i++)
{
dr[i] = dr[i].ToString();
}
}
You have to create the List<T>.
Something like this:
List<String[]> list=new List<String[]>();
if (dr.Length > 0)
{
for (int i = 0; i < dr.Length; i++)
{
string []ar=new string[dtget.Columns.Count];
for(int j=0;j<dtget.Columns.Count;j++)
{
ar[j]=dr[i][j].ToString();
}
list.Add(ar);
}
}
You've declared the array, but not instantiated it. and you're also not writing anything to the actual array, you're trying to write straight back to the datatable.
String[] Con= new String[dtget.Columns.Count];
for (int i = 0; i <= dr.Length; i++)
{
Con[i] = dr[i].ToString();
}
The problem is that you are assigning values to the datarrow in stead of to your string array.
Change
dr[i] = dr[i].ToString();
to
con[i] = dr[i].ToString();
also you are missing the new statement for Con:
Con = new String[dr.Table.Columns.Count];
notice that there is no such thing as dr.Length, you have to check for the column count:
dr.Table.Columns.Count
lastly, you should probably move the string array definition up so it's available outside the IF.
Depending on your needs, what you could do is use the Datarow's ItemArray property. It is an object array in stead of a string array, but before using it's values you can do a "ToString()" and you are all set.
string a = dr.ItemArray[i].ToString();
Related
is there a way to remove primary key from the datatable Or is there any way to remove the constraints of "PK" first and then remove the column itself?
Thanks!
UPDATED:
dtTable.Columns.Add(new System.Data.DataColumn("PRIMARY_KEY", typeof(System.Int32)));
dtTable.PrimaryKey = new DataColumn[1] { dtTable.Columns["PRIMARY_KEY"] }; // throws an error
dtTable.Columns["PRIMARY_KEY"].AutoIncrement = true;
You can remove primay key using
DataTable.PrimaryKey = null;
you can delete data table column using
DataTable.Columns.Remove("column name here");
I found that sometimes after removing PrimaryKey from a DataTable:
MyDataTable.PrimaryKey = null;
the Unique setting remains true on the member columns of the deleted PrimaryKey.
My solution:
public static void KillPrimaryKey(DataTable LocDataTable)
{
int LocPriKeyCount = LocDataTable.PrimaryKey.Length;
string[] PrevPriColumns = new string[LocPriKeyCount];
// 1. Store ColumnNames in a string Array
for (int ii = 0; ii < LocPriKeyCount; ii++) PrevPriColumns[ii] = LocDataTable.PrimaryKey[ii].ColumnName;
// 2. Clear PrimaryKey
LocDataTable.PrimaryKey = null;
// 3. Clear Unique settings
for (int ii = 0; ii < LocPriKeyCount; ii++) LocDataTable.Columns[PrevPriColumns[ii]].Unique = false;
}
Need help checking for a specific value in List<T> foreach loop. If there is specific value then display a specific string value.
For example how do I…
If (value.something_2 == "Null")
{
value.something_2 == ".";
}
Elseif (value.something_2 == " ")
{
value.something_2 == "0";
}
How would I incorporate the above example within the “foreach” loop?
See code below.
protected void MyReport(string filename, IMyRepository repository)
{
using (FileStream fileStream = new FileStream(Server.MapPath(#"~/Includes/") + filename, FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(fileStream))
{
List<Report> _report = repository.GetMyReport().ToList();
foreach (var value in _report)
{
String row01 = String.Format("{0, -10}{1, 23}{2, 120}{3, 8}",
value.somthing_1,
values.something_2,
value.something_3);
String row02 = String.Format("{0, -10}{1, 23}{2, 120}{3, 8}",
value.somthing_4,
values.something_5,
value.something_6);
Writer.WriteLine(row01);
Writer.WriteLine(row02);
}
}
writer.Close();
}
}
There is no clever built-in String.Format that you can do for this if that's what you have in mind. However, the compiler has some tricks that can reduce the amount of code you need to write e.g.
// if it's null, assign it to "."
var s2 = value.something_2 ?? ".";
// it can never be null here, so if there is whitespace default to "0"
value.something_2 = String.IsNullOrWhitespace(s2) ? "0" : s2;
If I'm understanding what you're saying, it might be easier just to have another function returning the (possibly) modified string and just pass each of your values into it, inline.
Sting row01 = String.Format("{0, -10}{1, 23}{2, 120}{3, 8}", myFunc(value.somthing_1), myFunc(values.something_2), myFunc(value.something_3));
and then have this in the same class
private string myFunc(string something){
if (something == “Null”){
return “.“;
} else if (something == “ “) {
return “0”;
} else {
return something;
}
}
I have 2 ArrayList, which contains the filenames, now one list has more names and other might have less, or sometime equal, i want to list the filenames which are not common in both arraylist and accordingly update the database, i was able to check whether they are equal or not, but i am unable to list which list has extra elements and which are they.
Here is a code which i am currently using.
ArrayList DatabaseSavedThumbnail = objSlideShow.GetAllThumbnailBySlideShowId();
string[] FolderSavedThumbnail = Directory.GetFiles(Server.MapPath("~/Portals/2/SlideShowThumbnails/" + SlideShowName));
if (Directory.GetFiles(Server.MapPath("~/Portals/2/SlideShowThumbnails/" + SlideShowName)).Length > 0)
{
if (!Object.Equals(DatabaseSavedThumbnail, FolderSavedThumbnail))
{
for (int i = 0; i < DatabaseSavedThumbnail.Count && i < FolderSavedThumbnail.Length; i++)
{
if (!object.Equals(DatabaseSavedThumbnail[i], FolderSavedThumbnail[i]))
{
if (DatabaseSavedThumbnail.Count > FolderSavedThumbnail.Length)
{
objSlideShow.Thumbnail = "/Portals/2/SlideShowThumbnails/" + SlideShowName + "/" + Path.GetFileName(DatabaseSavedThumbnail[i].ToString());
}
else
{
objSlideShow.Thumbnail = "/Portals/2/SlideShowThumbnails/" + SlideShowName + "/" + Path.GetFileName(FolderSavedThumbnail[i].ToString());
}
}
Response.Write(objSlideShow.Thumbnail + "<br>");
/*objSlideShow.SlideTitle = String.Empty;
objSlideShow.SlideDescription = string.Empty;
objSlideShow.AddSlide();*/
}
}
}
But this list all the elements of the arraylist which has more elements, i just want the differential elements, so that i can update the database with those elements only.
Can anyone tell me how could i get the differential records comparing 2 array list.
Try this to get elements not common in both lists (assuming DatabaseSavedThumbnail has strings):
using System.Linq;
...
...
var dstArray = DatabaseSavedThumbnail.ToArray(typeof(string));
var fstArray = FolderSavedThumbnail;
var notCommonElements = dstArray.Union(fstArray).Except(dstArray.InterSect(fstArray));
A very naive iterative approach can be:
private IEnumerable<string> GetNotCommonElements(string[] array1, string[] array2)
{
foreach (var item in array1)
{
if (!array2.Contains(item))
{
yield return item;
}
}
foreach (var item in array2)
{
if (!array1.Contains(item))
{
yield return item;
}
}
}
Then use it like:
foreach(var item in GetNotCommonElements(dstArray, fstArray))
{
// Do stuff with item
}
you can get idea from this
List<int> intersection = first.Cast<int>().Intersect(second.Cast<int>()).ToList();
or
ArrayList intersection = new ArrayList();
foreach (var i in first.Cast<int>().Intersect(second.Cast<int>()))
intersection.Add(i);
More detail
Two ArrayList manipulation
I am calling a web Method from javascript. The web method returns an array of customers from the northwind database. The example I am working from is here: Calling Web Services with ASP.NET AJAX
I dont know how to write this javascript method: CreateCustomersTable
This would create the html table to display the data being returned. Any help would be appreciated.
My javascript
function GetCustomerByCountry() {
var country = $get("txtCountry").value;
AjaxWebService.GetCustomersByCountry(country, OnWSRequestComplete, OnWSRequestFailed);
}
function OnWSRequestComplete(results) {
if (results != null) {
CreateCustomersTable(results);
//GetMap(results);
}
}
function CreateCustomersTable(result) {
alert(result);
if (document.all) //Filter for IE DOM since other browsers are limited
{
// How do I do this?
}
}
else {
$get("divOutput").innerHTML = "RSS only available in IE5+"; }
}
My web Method
[WebMethod]
public Customer[] GetCustomersByCountry(string country)
{
NorthwindDALTableAdapters.CustomersTableAdapter adap =
new NorthwindDALTableAdapters.CustomersTableAdapter();
NorthwindDAL.CustomersDataTable dt = adap.GetCustomersByCountry(country);
if (dt.Rows.Count <= 0)
{
return null;
}
Customer[] customers = new Customer[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
NorthwindDAL.CustomersRow row = (NorthwindDAL.CustomersRow)dt.Rows[i];
customers[i] = new Customer();
customers[i].CustomerId = row.CustomerID;
customers[i].Name = row.ContactName;
}
return customers;
}
Try to look what is the result variable value in debug mode. If the structure seems the structure that i'm imagining, something like this could work:
function CreateCustomersTable(result) {
var str = '<table>';
str += '<tr><th>Id</th><th>Name</th></tr>';
for ( var i=0; i< result.length; i++){
str += '<tr><td>' + result[i].CustomerId + '</td><td>' + result[i].Name + '</td></tr>';
}
str += '</table>';
return str;
}
And then You can do somethig like this:
var existingDiv = document.getElementById('Id of an existing Div');
existingDiv.innerHTML = CreateCustomersTable(result);
I wish this help you.
Something like this, assuming you have JSON returned in the "result" value. The "container" is a div with id of "container". I'm cloning nodes to save memory, but also if you wanted to assign some base classes to the "base" elements.
var table = document.createElement('table');
var baseRow = document.createElement('tr');
var baseCell = document.createElement('td');
var container = document.getElementById('container');
for(var i = 0; i < results.length; i++){
//Create a new row
var myRow = baseRow.cloneNode(false);
//Create a new cell, you could loop this for multiple cells
var myCell = baseCell.cloneNode(false);
myCell.innerHTML = result.value;
//Append new cell
myRow.appendChild(myCell);
//Append new row
table.appendChild(myRow);
}
container.appendChild(table);
You should pass the array as JSON or XML instead of just the toString() value of it (unless that offcourse is returns either JSON oR XML). Note that JSOn is better for javascript since it is a javascript native format.
Also the person who told you that browser other then IE can not do DOM manipulation should propably have done horrible things to him/her.
If your format is JSON you can just for-loop them and create the elements and print them. (once you figured out what format your service returns we can help you better.)
I'm creating a JsonArray such as:
JsonArray jsonValues = new JsonArray();
for( int i = 0; i < values.Count; i++ )
{
var someSingleValue = values[i];
jsonValues.Add( string.Format( "Name: {0}", someSingleValue ) );
}
After that I'm shipping json values to my javascript in .aspx page via call:
HtmlPage.Window.Invoke("call", jsonValues);
The call works and it gets there, however I have no idea how to iterate over those values, i.e extract them.
I've tried: (in javascript)
for (var x in somevalues){ alert(somevalues); }
I also tried:
for(var i = 0; i < somevalues.length; i++) {
alert(somevalues[i]);
}
but it crashes.(in both cases)
any ideas?
Are you using the eval method to serialize the string to a JSON object?
function call(somevalues){
//somevalues is currently just a string.
var results = eval("(" + somevalues +")");
//results now should contain your array as a JSON object.
//and you should be able to iterate over it at this point.
for(var i = 0; i < results.length; i++){
alert(results[i]);
}
}
Assuming somevalues is truly an array, you do it like this:
for(var i = 0; i < somevalues.length; i++) {
// do something with somevalues[i]
}
What you did was tell JavaScript to iterate over the properties of the somevalues object, which is similar, but not the same, as the iteration using a regular for loop.
EDIT: I am willing to bet your variable, somevalues is a string. Just do alert(somevalues) and see what happens.