hello again y have populate my datatable using 1 button an array, next button 2 is going to send my datatable to excel, so what a i do is this using C#, and asp.net:
out side of the button y declare my datable so i can be use in both buttons
System.Data.DataTable _myDataTable =new System.Data.DataTable();
button 1 fill datatable: for this example lets say only 10 columns, caract=number of cells
for (int k=0; k < 10; k++)
{
_myDataTable.Columns.Add();
}
for (int j=0; j < 10; j++)
{
TableRow r = new TableRow();
System.Data.DataRow row=_myDataTable.NewRow();
for (int i = 0; i < caract+1; i++)
{
row[i]=(datar[j,i].ToString());
}
_myDataTable.Rows.Add(row);
Table1.Rows.Add(r);
}
now button 2 allows to the user if he wants to save the data from the datatable to an excel, but first i verifi if the datable is empty
if(_myDataTable !=null || _myDataTable.Rows.Count == 0)
{
string name="productos";
Label2.Text="it has data";
}
else{Label2.Text="NO data"; }
no i recibe the text that i have data yupi for me, but when i press button 2 to send the datatable to excel, it creats the document however is empty,
so the next thing i would like to try is to verifi cell by cell if it has the data is supposed to have, but only have no idea how to extract the data from the datatable and to be display in a label.
I appreciate any help
Your if condition looks wrong on a couple of points.
This is how I would code it:
if(_myDataTable !=null && _myDataTable.Rows.Count > 0)
The above means - if _myDataTable is a valid object and it contains values.
JUAN you can define your DataTable in global scope. Then you can use it in both of your button event handlers.
For example:
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
private DataTable _myDataTable;
public DataTable MyDataTable {
get
{
return _myDataTable;
}
set
{
_myDataTable = value;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int k=0; k < 10; k++)
{
MyDataTable.Columns.Add();
}
for (int j=0; j < 10; j++)
{
TableRow r = new TableRow();
System.Data.DataRow row = MyDataTable.NewRow();
for (int i = 0; i < caract+1; i++)
{
row[i]=(datar[j,i].ToString());
}
MyDataTable.Rows.Add(row);
Table1.Rows.Add(r);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
if(MyDataTable !=null || MyDataTable.Rows.Count == 0)
{
string name="productos";
Label2.Text="it has data";
}
else
{
Label2.Text="NO data";
}
}
}
}
I know this is an old question but there is an easy way to solve this right now as follows:
if ((dataTableName?.Rows?.Count ?? 0) > 0)
Related
as the Problem in the title says, I am having Problems importing Data from a txt file into a datagridview. I get the error Input Array is longer than the number of columns. Here is what I am using to save my Data from the datagridview into a txt file and what I want to use to Import the data into the datagridview:
private void OpenFile_Click(object sender, EventArgs e)
{
string[] lines = File.ReadAllLines(#"C:\Users\gv9816\source\repos\Liste\UserData.txt");
string[] values;
for (int i = 0; i < lines.Length; i++)
{
values = lines[i].ToString().Split('|');
string[] row = new string[values.Length];
for (int j = 0; j < values.Length; j++)
{
row[j] = values[j].Trim();
}
_table.Rows.Add(row);
}
}
private void SaveFile_Click_1(object sender, EventArgs e)
{
TextWriter writer = new StreamWriter(#"C:\Users\gv9816\source\repos\Liste\UserData.txt");
for (int i = 0; i < _table.Rows.Count - 1; i++)
{
for (int j = 0; j < _table.Columns.Count; j++)
{
writer.Write("\t" + DataGridViewCell.Rows[i].Cells[j].Value.ToString() + "\t");
}
writer.WriteLine("");
}
writer.Close();
MessageBox.Show("Data Exported");
}
Also, here is what I use to create the columns:
private void Form1_Load(object sender, EventArgs e)
{
_table.Columns.Add("First Name", typeof(string));
_table.Columns.Add("Last Name", typeof(string));
_table.Columns.Add("Age", typeof(int));
DataGridViewCell.DataSource = _table;
}
Here is the Output in my UserData.txt file
Hans | Müller | 12 |
Here is what the application Looks like
And this is what is generated into the UserData file
Any help would be appreciated :)
The last | character is the problem, If you can't change the data inside txt file. Just change this line,
values = lines[i].ToString().Split('|');
to this,
values = lines[i].ToString().Split('|').Where(x => !string.IsNullOrEmpty(x)).ToArray();
I have a checkedListBox1 and i want to convert all it's items to a DataGridView
i have the following code
string[] ar = new string[60];
for (int j = 0; j < checkedListBox1.Items.Count; j++)
{
ar[j] = checkedListBox1.Items[j].ToString();
}
dataGridView2.DataSource = ar;
but the dataGridView2 is filled with the length of the item instead of the item itself, can any one help?
These code blocks may give an idea (all is worked for me). CheckedListBox items returns a collection. It is coming from IList interface so if we use a List item as datasource for datagridview solves the problem. I used genericList as an additional class of Sample. When we use string array datagridview shows each items length. In here overried ToString returns original value.
class Sample
{
public string Value { get; set; }
public override string ToString()
{
return Value;
}
}
In form class:
private void button1_Click(object sender, EventArgs e)
{
CheckedListBox.ObjectCollection col = chk.Items;
List<Sample> list = new List<Sample>();
foreach (var item in col)
{
list.Add(new Sample { Value = item.ToString() });
}
dgw.DataSource = list;
}
This simple DataTable code appears to work...
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
for (int j = 0; j < checkedListBox1.Items.Count; j++) {
dt.Rows.Add(checkedListBox1.Items[j].ToString());
}
dataGridView1.DataSource = dt;
Because DataGridView looks for properties of containing objects. For string there is just one property - length. So, you need a wrapper for a string like this.
string[] ar = new string[60];
for (int j = 0; j < checkedListBox1.Items.Count; j++)
{
ar[j] = checkedListBox1.Items[j].ToString();
}
dataGridView1.DataSource = ar.Select(x => new { Value = x }).ToList();
I have 2 datatables I am trying to compare. I would like on button press to compare the 2 data tables and if there is a matching record between both data tables to have datatable 1's associated column highlighted in red.
Example:
Before button click
dt1
john
sallybilly
dt2
billy
after button click
dt1
john
sallybilly <-- This would be highlighted red
dt2
billy
I tried the following but was unable to get it to work correctly:
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < table.Rows.Count; i++)
{
var row1 = table.Rows[i].ItemArray;
var row2 = csv_datatable.Rows[i].ItemArray;
for (int j = 0; j < row1.Length; j++)
{
if (!row1[j].ToString().Equals(row2[j].ToString()))
{
csv_datagridview.Rows[i].Cells[j].Style.BackColor = Color.Red;
}
I have also tried the following to see if I can get at least the correct amount of popups to display, but no bueno:
private void button1_Click(object sender, EventArgs e)
{
foreach (DataRow rowSampleOne in csv_datatable.Rows)
{
string injuredplayers = rowSampleOne[0].ToString();
foreach (DataRow rowSampleTwo in table.Rows)
{
if (rowSampleTwo[0].ToString().Equals(injuredplayers))
{
MessageBox.Show("Something to see");
}
else
{
//do nothing
}
}
}
}
In this sample:
if (!row1[j].ToString().Equals(row2[j].ToString()))
{
csv_datagridview.Rows[i].Cells[j].Style.BackColor = Color.Red;
}
You're turning the background red if the names are not equal. Try something like this:
for (int i = 0; i < table.Rows.Count; i++)
{
var row1 = table.Rows[i].Items[0]
foreach (DataRow dr in csv_datatable.Rows)
{
if (row1.ToString().Equals(dr.Items[0].ToString()))
{
csv_datagridview.Rows[i].Cells[0].Style.BackColor = Color.Red;
break;
}
}
}
Hi I want to add my checkedboxList checked values inside grid view(Asp.net), below existing rows how can I do this. This is the code how I tried but that is not correctly adding
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
// check view state is not null
if (ViewState["MailTracking"] != null)
{
//get datatable from view state
dt = (DataTable)ViewState["MailTracking"];
DataRow oItem = null;
if (dt.Rows.Count > 0)
{
for (int i = 1; i <= dt.Rows.Count; i++)
{
oItem = dt.NewRow();
string strValue = "";
for (int k = 0; k < CheckBoxListBranch.Items.Count; k++)
{
if (CheckBoxListBranch.Items[k].Selected)
{
strValue = CheckBoxListBranch.Items[k].Value;
oItem[0] = CheckBoxListBranch.Items[k].Text;
}
}
}
//Remove initial blank row
if (dt.Rows[0][0].ToString() == "")
{
dt.Rows[0].Delete();
dt.AcceptChanges();
}
dt.Rows.Add(oItem);
ViewState["MailTracking"] = dt;
GVDisplay.DataSource = dt;
GVDisplay.DataBind();
}
}
}
My asp:CheckBoxList ID is: CheckBoxListBranch I used onselectedindexchanged="CheckBoxList1_SelectedIndexChanged" inside asp:CheckBoxList.
I think you meant the below code statement
oItem[0] = CheckBoxListBranch.Items[k].Text;
to actually be, notice that it's oItem[k] else every time you are adding/re-ading the element to the first column of the row
oItem[k] = CheckBoxListBranch.Items[k].Text;
Per your comment: in that case you should move the code line dt.Rows.Add(oItem); inside your for loop as below
for (int k = 0; k < CheckBoxListBranch.Items.Count; k++)
{
if (CheckBoxListBranch.Items[k].Selected)
{
strValue = CheckBoxListBranch.Items[k].Value;
oItem[0] = CheckBoxListBranch.Items[k].Text;
dt.Rows.Add(oItem);
}
}
i have gridview with a combo box column Named ColumnLocationDemo. I want to ensure that user every time selected distinct option from comobox. i am trying this code message box appearing but dont know how to change the index of columnLocationDemo?? there is not selectedIndex property in this gvCombobox
private void dataGridView1_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
string str1 = dataGridView1.CurrentRow.Cells[1].Value.ToString();
for (int i = 0; i < dataGridView1.Rows.Count - 2; i++)
{
string str = dataGridView1.Rows[i].Cells[1].Value.ToString();
if (str==str1)
{
MessageBox.Show("same occur");
ColumnLocationDemo
}
}
}
How about this...
Don't use the currentRow. Just compare the new value with the values already selected.
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = i + 1; j < dataGridView1.Rows.Count - 1;j++ )
{
if (dataGridView1.Rows[i].Cells[0].Value.ToString() == dataGridView1.Rows[j].Cells[0].Value.ToString())
{
dataGridView1.Rows[j].Cells[0].Value = "";
}
}
}
columnLocationDemo.SelectedIndex = 0;
If that is the name of your comboBox. Also you can select any index.
Try this:
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
//your work;
}