saving data from datagrid c# - datagrid

hi guys i am new to c# and i was making a text editor program using data grid view. The problem is when i open a text file to my data grid, then when i press save i get the error saying "Index was outside the bounds of the array". I included my code below. Any suggestions can be a big help for me. I included my code below.
// edit file button
dataGridView1.Columns.Add("colname", "Question");
dataGridView1.Columns.Add("colname", "Answer 1");
dataGridView1.Columns.Add("colname", "Answer 2");
dataGridView1.Columns.Add("colname", "Answer 3");
dataGridView1.Columns.Add("colname", "Answer 4");
dataGridView1.Columns.Add("colname", "Correct Answer");
dataGridView1.Columns[5].ReadOnly = true;
dataGridView1.Columns[5].DefaultCellStyle.BackColor = Color.DimGray;
dataGridView1.AllowUserToAddRows = true;
StreamReader sr = new StreamReader(fName);
string Contents = sr.ReadToEnd();
string[] strArray = { Contents };
for (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
{
for (int c = 0; c <= dataGridView1.Columns.Count - 1; c++)
{
dataGridView1.Rows.Add(strArray[r].Split('|')); //getting the error here
}
}
//save button
private void button2_Click(object sender, EventArgs e)
{
//dataGridView1.AllowUserToAddRows = false;
if (dataGridView1.Visible)
{
string fName = "C:\\Documents and Settings\\" + txtFileName.Text + ".txt";
System.IO.StreamWriter file = new System.IO.StreamWriter(fName);
string sLine = "";
for (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
{
for (int c = 0; c <= dataGridView1.Columns.Count - 1; c++)
{
sLine = sLine + dataGridView1.Rows[r].Cells[c].Value;
if (c != dataGridView1.Columns.Count - 1)
{
sLine = sLine + "|";
}
}
file.WriteLine(sLine);
sLine = "";
}
file.Close();
System.Windows.Forms.MessageBox.Show("Save Complete.", "Program Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
dataGridView1.DataSource = "";
dataGridView1.Visible = false;
}
else
{
string cap = "Confirmation";
string message = "Nothing to save";
MessageBoxButtons Btn2 = MessageBoxButtons.OK;
MessageBox.Show(message, cap, Btn2);
}
}
Thanks again for the help

Initially there is a dataGridView1.Rows.Count
Inside the loop u r doing this
dataGridView1.Rows.Add, which increments dataGridView1.Rows.Count by 1 every single time
so it comes back into the loop after the processing
try declaring int gridRowcount = dataGridView1.Rows.Count;
and then replace (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
for (int r = 0; r <= gridRowcount - 1; r++) and try
just guessing

Related

ASP.NET - Input string was not in a correct format

I am getting an error saying my input string was not in a correct format when I try to get, multiply and display I stored data's in cookies.
It says there was an error in a part in total = total + (Convert.ToInt32(a[2].ToString()) * Convert.ToInt32(a[3].ToString()));
Somebody help me please. Here is my code:
protected void Page_Init(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[7] { new DataColumn("product_name"), new DataColumn("product_desc"), new DataColumn("product_price"), new DataColumn("product_qty"), new DataColumn("product_images"), new DataColumn("id"), new DataColumn("product_id") });
if (Request.Cookies["aa"] != null)
{
s = Convert.ToString(Request.Cookies["aa"].Value);
string[] strArr = s.Split('|');
for (int i = 0; i < strArr.Length; i++)
{
t = Convert.ToString(strArr[i].ToString());
string[] strArr1 = t.Split(',');
for (int j = 0; j < strArr1.Length; j++)
{
a[j] = strArr1[j].ToString();
}`enter code here`
dt.Rows.Add(a[0].ToString(), a[1].ToString(), a[2].ToString(), a[3].ToString(), a[4].ToString(), i.ToString(), a[5].ToString());
total = total + (Convert.ToInt32(a[2].ToString()) * Convert.ToInt32(a[3].ToString()));
totalcount = totalcount + 1;
cart_items.Text = totalcount.ToString();
cart_price.Text = total.ToString();
}
}
I recomment you to use int.TryParse(...) if you want to convert form string.
It could be like this:
int var2, var3 = 0;
if(int.TryParse(a[2].ToString(), out var2)
&& int.TryParse(a[3].ToString(), out var3))
{
total += (var2 * var3);
}

unable to download xlsx file using POI

Hi i working on poi poc to generate xlsx file in webapplication i was able to render excel standalone well but when i integrate codebase in my project i was getting below error.
below is code base base to download xlsx file in webapplication
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("Sheet1");
XSSFRow row = spreadsheet.createRow(0);
XSSFCell cell;
while (response.nextResultSet()) {
resultSet = response.getResultSet();
Object[] columnMetaData = resultSet.getColumnNames();
int columnCount = columnMetaData.length;
//Columns Loop
ArrayList<String> columns = new ArrayList<String>();
for (int i = 1; i < columnCount; i++) {
String columnName = (String) columnMetaData[i];
columns.add(columnName);
cell = row.createCell(i-1);
cell.setCellValue(columnName);
}
int i=1;
while (resultSet.nextRow()) {
row = spreadsheet.createRow(i);
i++; // counter for each row of data
for (int j = 0; j < columnMetaData.length; j++)
{
String keyVal = String.valueOf(columnMetaData[j]);
String value = (String)resultSet.getValue(keyVal);
cell = row.createCell(j);
cell.setCellValue(value);
}
}
log.info("value if i--->" + i);
for (int k = 1; k < columnCount; k++) {
spreadsheet.autoSizeColumn(k-1);
}
}
ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
workbook.write(outByteStream);
context.getResponse().setHeader("content-disposition", "inline;filename=" + calendar.getTimeInMillis() + ".xlsx");
context.getResponse().setContentType("application/Excel");
context.getRequest().setAttribute("called_from", "excel");
//context.getResponse().setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//context.getResponse().setHeader("Content-Disposition", "attachment; filename=testxls.xlsx");
}
OutputStream os = null;
os = context.getResponse().getOutputStream();
byte [] outArray = is.toByteArray();
context.getResponse().setContentLength(outArray.length);
os.write(outArray);
log.info(os.toString());
os.flush();

Create 2 or more text files with ASP.NET

I have created a web app which creates 1 text file. Inside this text file it is created 1000 rows with the same word "TRY AGAIN". After this each 50 rows I put a random code which means in 1000 rows, 20 rows are random.
This is my code:
static Random randNum = new Random();
public static string Random(int ran)
{
string _charachters = "ABCDEFGHIJKMLNOPQRSTUVWXYZ0123456789";
char[] chars = new char[ran];
int allowedCharCount = _charachters.Length;
for (int i = 0; i < ran; i++)
{
chars[i] = _charachters[(int)((_charachters.Length) * randNum.NextDouble())];
}
return new string(chars);
}
protected void Button1_Click(object sender, EventArgs e)
{
string pathCreate = #"C:\" + TextBox3.Text + ".txt";
if (!File.Exists(pathCreate))
{
using (StreamWriter sw = File.CreateText(pathCreate))
{
for (int i = 1; i <= int.Parse(TextBox1.Text); i++)
{
sw.WriteLine("TRY AGAIN.");
}
}
}
string pathRandom = #"C:\" + TextBox3.Text + ".txt";
string[] lines = File.ReadAllLines(pathRandom);
for (int i = 0; i < lines.Length; i += int.Parse(TextBox2.Text))
{
lines[i] = lines[i].Replace("TRY AGAIN.", Random(int.Parse("7")));
}
File.WriteAllLines(pathRandom, lines);
}
Now I want to create 2 ore more text files with one click of a button. And on each text file there will be random codes (not duplicates). Any idea?
Thank You.
I found the solution. It is late in my country and my brain barely works. :P
for(int j = 1; j <= 10; j++)
{
string pathKrijo = #"C:\inetpub\wwwroot\KODET\" + j.ToString() + ".txt";
using (StreamWriter sw = File.CreateText(pathKrijo))
{
for (int i = 1; i <= 100; i++)
{
sw.WriteLine("Provo Përsëri.");
}
}
string pathKodFitues = #"C:\inetpub\wwwroot\KODET\" + j.ToString() + ".txt";
string[] lines = File.ReadAllLines(pathKodFitues);
for (int i = 0; i < lines.Length; i += 10)
{
lines[i] = lines[i].Replace("Provo Përsëri.", Random(int.Parse("7")));
}
File.WriteAllLines(pathKodFitues, lines);
}

Why the line XXX showing an error saying java.lang.ArrayIndexOutOfBoundsException?

//Firstly I need to create a 2-D array of floating points(randomly generated) and store them in a text file no of rows and columns are user input
import java.io.;
import java.util.;
public class ClaransS {
public static void main(String args[]) throws IOException {
// *********************************************************************
// Variables declaration n-no.of rows k-forget it for now n_o_d-no. of
// columns
// *********************************************************************
int n, k, n_o_d;
// *********************************************************************
// Creating the text file to store data
// *********************************************************************
File f = new File("C:/x/y/clarans.text");
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
// *********************************************************************
// Taking user inputs
// *********************************************************************
Scanner userInputScanner = new Scanner(System.in);
System.out.println("Enter the no. of data you want to cluster");
n = userInputScanner.nextInt();
System.out.println(n);
System.out.println("Enter the no. of clusters you want to form");
k = userInputScanner.nextInt();
System.out.println(k);
System.out
.println("Enter the no. of dimensions each data will be in a space of");
n_o_d = userInputScanner.nextInt();
System.out.println(n_o_d);
userInputScanner.close();
// *********************************************************************
// Storing random data in the data-set
// *********************************************************************
double data_set[][] = new double[n][n_o_d];
int count = 1;
int i = 0;
int j = 1;
for (i = 0; i < n; i++) {
data_set[i][0] = count;
for (j = 1; j <= n_o_d; j++) {
//THIS LINE GIVES ERROR
data_set[i][j] = (double) Math.random();//YES THIS ONE XXX
}
count++;
}
for (i = 0; i < n; i++) {
for (j = 0; j <= n_o_d; j++) {
try (PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(f, true)))) {
out.print(data_set[i][j] + "\t");
} catch (IOException e) {
}
}
try (PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(f, true)))) {
out.println();
}
}
}
}
The error is in test condition of for
(j = 1; j <= n_o_d; j++).
Test condition will be j < n_o_d

The IListSource does not contain any data sources.during next page is clicked in gridview

Lbl_Username.Text = FirstName + " " + LastName;
if (!IsPostBack)
{
ds = objSun.FetchTravelDetails(userId);
int datasetcount = ds.Tables[0].Rows.Count;
if (datasetcount == 0)
{
dt.Columns.Add("request_ID");
dt.Columns.Add("userId");
dt.Columns.Add("");
dt.Columns.Add("status");
dt.Columns.Add("remark");
dt.Columns.Add("");
for (int i = 0; i < 9; i++)
{
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
}
GridView_RequisitionManagement.DataSource = dt;
GridView_RequisitionManagement.DataBind();
}
else
{
GridView_RequisitionManagement.DataSource = ds;
GridView_RequisitionManagement.DataBind();
}
}
}
protected void GridView_RequisitionManagement_RowDataBound(object sender, GridViewRowEventArgs e)
{
int datasetcount1 = ds.Tables[0].Rows.Count;
if (datasetcount1 != 0)
{
for (int i = 0; i < GridView_RequisitionManagement.Rows.Count; i++)
{
LinkButton lnk_view = new LinkButton();
lnk_view = GridView_RequisitionManagement.Rows[i].FindControl("LinkBtn_ViewFullDetails_GridView_LeaveManagement") as LinkButton;
int type = Convert.ToInt32(ds.Tables[0].Rows[i]["request_Type"].ToString());
string typeName = "";
string requestId = GridView_RequisitionManagement.DataKeys[i][0].ToString();
string request_userId = GridView_RequisitionManagement.DataKeys[i][1].ToString();
switch (type)
{
case 2:
{
typeName = "Travel Request";
lnk_view.PostBackUrl = "Status_ViewDetails_TravelClaims.aspx?requestId=" + requestId;
break;
}
case 3:
{
typeName = "Other Claims";
lnk_view.PostBackUrl = "Status_ViewDetails_OtherClaims.aspx?requestId=" + requestId;
break;
}
case 4:
{
typeName = "Petty cash";
lnk_view.PostBackUrl = "Status_ViewDetails_PettyCashVoucher.aspx?requestId=" + requestId;
break;
}
case 5:
{
typeName = "Advance";
lnk_view.PostBackUrl = "Status_ViewDetails_AdvanceRequisitions.aspx?requestId=" + requestId;
break;
}
}
GridView_RequisitionManagement.Rows[i].Cells[1].Text = Convert.ToDateTime(ds.Tables[0].Rows[i]["date"].ToString()).ToShortDateString();
GridView_RequisitionManagement.Rows[i].Cells[2].Text = typeName;
}
}
else
{
for (int j = 0; j < GridView_RequisitionManagement.Rows.Count; j++)
{
GridViewRow rows = GridView_RequisitionManagement.Rows[j];
LinkButton lnk_grd_views = (LinkButton)rows.FindControl("LinkBtn_ViewFullDetails_GridView_LeaveManagement") as LinkButton;
lnk_grd_views.Visible = false;
}
}
}
protected void GridView_RequisitionManagement_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView_RequisitionManagement.PageIndex = e.NewPageIndex;
GridView_RequisitionManagement.DataSource = ds;
GridView_RequisitionManagement.DataBind();
}
Hi guys, I need some help here. I'm using the above code to display the details
in the GridView. The DataTable and DataSet are used to populate the GridView. Now I want to do paging in the GridView, but when the next page is clicked it shows the following error:
The IListSource does not contain any data sources
and the next page in the grid shows empty.
Please assist me with this.
It seems as though you are only setting the DataSet 'ds' if it isn't a postback. So when the PageIndexChanging event is run ds is not going to be set to a dataset.
Try moving
ds = objSun.FetchTravelDetails(userId);
Above the if(!IsPostback) line.

Resources