Passing array of strings from c# to javascript - c#

I am building two arrays in c# and pass them to a js function like this:
//call js to show the map with the markers
string[] lats = new string[10];
string[] longs = new string[10];
for (int i = 0; i < 10; i++)
{
lats[i] = dv[i]["Latitude"].ToString();
}
for (int i = 0; i < 10; i++)
{
longs[i] = dv[i]["Longitude"].ToString();
}
StringBuilder sbLats = new StringBuilder();
string[] latsArray = lats.ToArray<string>();
//Build the JS array.
sbLats.Append("[");
for (int i = 0; i < latsArray.Length; i++)
{
sbLats.AppendFormat("'{0}', ", latsArray[i]);
}
sbLats.Append("]");
StringBuilder sbLongs = new StringBuilder();
string[] longsArray = longs.ToArray<string>();
//Build the JS array.
sbLongs.Append("[");
for (int i = 0; i < longs.Length; i++)
{
sbLongs.AppendFormat("'{0}', ", longsArray[i]);
}
sbLongs.Append("]");
ScriptManager.RegisterStartupScript(this, this.GetType(), "mapMarket", "buildMapWithMarkers('map_market', " + latsArray + ", " + longsArray + ", " + "false" + ");", true);
For some unknown reason this throws an exception here (in the aspx page, part of generated js):
buildMapWithMarkers('map_market', System.String[], System.String[], false)
which says:
Uncaught SyntaxError: Unexpected token ]
Can you please tell me where I am wrong?

Solved it using #Skilwz suggestion (JavaScriptSerializer):
//call js to show the map with the markers
string[] lats = new string[10];
string[] longs = new string[10];
for (int i = 0; i < 10; i++)
{
lats[i] = dv[i]["Latitude"].ToString();
}
for (int i = 0; i < 10; i++)
{
longs[i] = dv[i]["Longitude"].ToString();
}
string serializedLat = (new JavaScriptSerializer()).Serialize(lats);
string serializedLong = (new JavaScriptSerializer()).Serialize(longs);
ScriptManager.RegisterStartupScript(this, this.GetType(), "mapMarket", "buildMapWithMarkers('map_market', " + serializedLat + ", " + serializedLong + ", " + "false" + ");", true);

Related

How can I write a loop to set the value of sum[i] and delete datatable columns where sum[i] <= 0

int i = 0;
string[] sum = new string[256];
for (i = 1; i < 256; i++)
{
sum[i] = sum[i].ToString();
sum[i] = Convert.ToInt32(dt.Compute("Sum(BIN" + i.ToString() + ")", string.Empty));
if(sum[i] == 0)
{
dt.Columns.Remove("BIN"+i.ToString()+"");
}
}
There is a problem where you're trying to assign an int to sum[i], because sum is a string[], and you can't assign an int to one of the items.
Instead, it seems you want to get the return value from the method and save it in a variable so you can compare it. In order to do this, we can modify the code like:
string[] sum = new string[256];
for (int i = 1; i < 256; i++)
{
int result = Convert.ToInt32(dt.Compute("Sum(BIN" + i.ToString() + ")", string.Empty));
if (result <= 0)
{
dt.Columns.Remove("BIN" + i.ToString() + "");
}
}
This can be simplified further by using the return value of the method directly in the if condition. We can also use interpolated strings instead of concatenation:
string[] sum = new string[256];
for (i = 1; i < sum.Length; i++)
{
if(Convert.ToInt32(dt.Compute($"Sum(BIN{i})", string.Empty)) <= 0)
{
dt.Columns.Remove($"BIN{i}");
}
}

Debug.Log() A 2D array from a custom class to main class

Here's my code.
CustomClass.cs
class ScoreBoard(){
private int m_lastCnt;
public ScoreBoard{
m_lastCnt = 0;
}
public void makeBoard(string history) {
string[] arrPartStr = history.Split(',');
int[] arrPart = new int[arrPartStr.Length];
for (int c = 0; c < arrPart.Length; c++)
{
int temp = 0;
if (arrPartStr[c][0] == 'P') temp = 100;
else if (arrPartStr[c][0] == 'B') temp = 200;
else temp = 300;
if (arrPartStr[c][1] == 'P') temp += 10;
if (arrPartStr[c][2] == 'P') temp += 1;
arrPart[c] = temp;
}
//var strTmp : String = strData;
//strTmp = "311|101|211|211|211|211|211|211|211|211|111|111|111|111|111|111|111|111|111"
//strTmp = strData.replace(/:/g,"");
int[,] arrTmp = new int[6100, 104];
}
}
Main Class i call the void method like this
ScoreBoard sb = ScoreBoard();
string history = "s ,o ,m ,e ,s ,t ,r ,i ,n ,g";
private void Start(){
sb.makeBoard(history);
}
How can i print my 2D array in my console?
I tried doing it like the for(int row){for(int col){}} but its not working i don't know why
Do you mean this?
for (int j = 0; j < arrTmp.GetLength(1); j++)
{
for (int i = 0; i < arrTmp.GetLength(0); i++)
{
var msg = "[" + i.ToString() + ", " + j.ToString() + "] = " + arrTmp[i, j].ToString();
Debug.Log(msg);
}
}
I got it to display:)
CustomClass.cs
int[,] arrTmp = new int[104, 6];
public int[,] GetBoard(){ return arrTmp }
MainClass.cs
int[,] arrayBigRoad = bsb.GetBoard();
for (int j = 0; j < arrTmp.GetLength(1); j++)
{
for (int i = 0; i < arrTmp.GetLength(0); i++)
{
var msg = "[" + i.ToString() + ", " + j.ToString() + "] = " + arrTmp[i, j].ToString();
Debug.Log(msg);
}
}
Thanks though Rodrigo . I'll mark yours as an answer

Create files in multiple folders

I've created a for loop that creates n folders. I would like to create a text file in each folder. How do i do it?
for (int i = 1; i < 17; i++)
{
System.IO.Directory.CreateDirectory(
String.Format(#"C:\Users\xxx\Desktop\xx\Test{0:d2}", i));
}
I found a better solution.
for (int i = 1; i < 17; i++)
{
Directory.CreateDirectory(String.Format(#"C:\Users\xxx\Desktop\xx\Test"+i, i));
if (!File.Exists(string.Format(#"C:\Users\xxx\Desktop\xx\Test{0}/Test.txt", i)))
{
File.WriteAllText(string.Format(#"C:\Users\xxx\Desktop\xx\Test{0}/Test.txt", i), " ");
}
Try this
for (int i = 1; i < 17; i++)
{
var folder = System.IO.Directory.CreateDirectory(String.Format(#"C:\Users\xxx\Desktop\xx\Test{0:d2}", i));
System.IO.File.WriteAllText(folder.FullName + #"\WriteText.txt", "your text content");
}
Update
if you want more than one file
for (int i = 1; i < 17; i++)
{
var folder = System.IO.Directory.CreateDirectory(String.Format(#"C:\Users\xxx\Desktop\xx\Test{0:d2}", i));
System.IO.File.WriteAllText(folder.FullName + #"\WriteText1.txt", "your text content 1");
System.IO.File.WriteAllText(folder.FullName + #"\WriteText2.txt", "your text content 2");
}
Try this:
var desktop_path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
for (int i = 1; i < 17; i++)
{
var folder_path = System.IO.Path.Combine(desktop_path, String.Format(#"xx\Test{0:d2}", i));
var file_path = System.IO.Path.Combine(folder_path, "file.txt");
System.IO.Directory.CreateDirectory(folder_path);
System.IO.File.WriteAllText(file_path, "content");
}
This code finds the current user's desktop path, and then uses System.IO.Path.Combine to ensure that paths are correctly concatenated together.
for (int i = 1; i < 17; i++)
{
var dir = System.IO.Directory.CreateDirectory
(String.Format(#"C:\Users\xxx\Desktop\xx\Test{0:d2}", i));
System.IO.File.Create(dir.FullName+ #"\MyFile.txt");
}
To create add content on the file, we can use FileStream object returned by File.Create()
Try this above,
I hope this may easy for you
string path = #"d:\\dummyfolder";
for (int i = 0; i < 17; i++)
{
string _folderPath = string.Format("{0}\\{1}", path, i);
if (!Directory.Exists(_folderPath))
{
//creating folder
Directory.CreateDirectory(_folderPath);
//creating text file
string _filePath = string.Format("{0}\\{1}\\{1}.txt", path, i);
string text = i + " " + "Content of the text file ";
File.WriteAllText(_filePath, text);
}
}

text files with string arrays get position substring

I am having a problem with the following:
I am loading a file into C# and then I am splitting it by lines with this code.
// Splitting by line from original file
string[] lines = showText.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
Now I need a for loop that will go through lines and get Substring from those lines, separately.
Here is what I am trying to accomplish, in a way:
for (int i = 0; i < lines.Length; i++)
{
int[] testing = new int[i];
testing[i] = int.Parse(lines[i].Substring(16, 1));
textBox1.Text = testing.ToString();
}
The error here is: Index was outside the bounds of the array.
Here is a picture also to get better idea as to what I'm trying to do.
http://s30.postimg.org/jbmjmqv1t/work.jpg
textBox1.Text = lines[0].Substring(16,1) + " " + lines[0].Substring(23,9);
textBox1.Text = lines[1].Substring(16,1) + " " + lines[1].Substring(23,9); //etc
Could anyone help me with this?
You are creating the array in the for loop, so it is being created for each line and with the wrong length. Instead of this part of the code:
for (int i = 0; i < lines.Length; i++)
{
int[] testing = new int[i];
testing[i] = int.Parse(lines[i].Substring(16, 1));
textBox1.Text = testing.ToString();
}
you should be doing this:
int[] testing = new int[lines.Length];
for (int i = 0; i < lines.Length; i++)
{
testing[i] = int.Parse(lines[i].Substring(16, 1));
textBox1.Text = testing.ToString();
}
This is how I've solved it.
int[] testing = new int[lines.Length];
textBox1.Clear(); //Just to clear it if button pressed again
for (int i = 0; i < lines.Length; i++)
{
testing[i] = int.Parse(lines[i].Substring(16, 1));//just getting the needed value
textBox1.Text += testing[i].ToString() + "\r\n" ;//adding each value to textBox1, separated by new line
}

pass 2d array from code behind to javascript

I have a DataTable that I get from the DB, I want to create a 2d array in the code behind (once I get the DataTable..), and then pass it as a 2d array to Javascript.
this is what I tried to code :
int[,] videoQarray = new int[dt_questionVideo.Rows.Count,dt_questionVideo.Columns.Count ];
string[,] videoQarrayTitle = new string[dt_questionVideo.Rows.Count, dt_questionVideo.Columns.Count ];
for (var i = 0; i < dt_questionVideo.Rows.Count ; i++)
{
for (int j = 0; j < dt_questionVideo.Columns.Count; j++)
{
videoQarray[i,j] = Convert.ToInt32(dt_questionVideo.Rows[i][0]);
videoQarrayTitle[i,j] = dt_questionVideo.Rows[i][1].ToString();
}
}
string createArrayScript = string.Format("var videQarray = [{0}];", string.Join(",", videoQarray));
createArrayScript += string.Format("var videQarrayList = [{0}];", string.Join(",", videoQarrayTitle));
Page.ClientScript.RegisterStartupScript(this.GetType(), "registerVideoQArray", createArrayScript, true);
well, in the browser console it says that videoQarray is not defined..
I wonder how can I do that properly..
Probably the variable is being defined inside a function and therefore is hidden for other parts of code. Try "window.videoQArray" insted of "var ":
string createArrayScript = string.Format("window.videQarray = [{0}];", string.Join(",", videoQarray));
createArrayScript += string.Format("window.videQarrayList = [{0}];", string.Join(",", videoQarrayTitle));
Edit: It's a 2d array (ok, you wrote that very clearly in the question but I didn't see). Use JavaScriptSerializer:
var serializer = new JavaScriptSerializer();
string createArrayScript = string.Format("window.videQarray = {0};", serializer.Serialize(videoQarray));
createArrayScript += string.Format("window.videQarrayList = {0};", serializer.Serialize(videoQarrayTitle));
Use The following function:
public static string ArrayToString2D(string[,] arr)
{
StringBuilder str = new StringBuilder();
str.Append("[['");
for (int k = 0; k < arr.GetLength(0); k++)
{
for (int l = 0; l < arr.GetLength(1); l++)
{
if (arr[k, l] == null)
str.Append("','");
else
str.Append(arr[k, l].ToString() + "','");
}
str.Remove(str.Length - 2, 2);
str.Append("],['");
}
str.Remove(str.Length - 4, 4);
str.Append("]]");
return str.ToString();
}
in the code behind have the following properties:
private string[,] upperLabels ;
public string UpperLabel
{
get
{ return Utils.ArrayToString2D(upperLabels); }
}
in the javascript use the following :
var upperSplitted = <%=UpperLabel%> ;
var value = upperSplitted[0][0];

Categories

Resources