c# how do i check if datasource is null? - c#

i have a control on a winform called chart1.
i would like to know whether chart1.DataSource is empty
how do i check it?

If the DataSource is a DataTable, you can check first that the DataTable is not null, and secondly that its Rows.Count > 0.
If the DataSource is a DataSet, you check for null, then tables, then rows.

Check to see if it is null.
if(chart1.DataSource == null)
{
// Do something
}
If you know what the DataSource is, then you can cast it and check to see if it is empty or not. For example:
List<String> strings = new List<String>() { "a", "b" };
// Set chart1.DataSource to strings... then later on
if(chart1.DataSource != null)
{
List<String> boundStrings = chart1.DataSource as List<String>;
if(boundStrings != null && boundStrings.Count > 0)
{
// do something
}
}

personally id check the datasource for null BEFORE I bind it to chart so I don't have to worry about chart1 dealing with a null datasource

if (chart1.DataSource == null)
{
// The DataSource is empty
}

Related

bind arraylist to dropdown menu list c#

I want to bind my arraylist to dropdown menu list. Here is my code.
I'm a beginner to C#. Please help.
if (selectinidialog.ShowDialog() == DialogResult.OK)
{
selectinibtn.Text = selectinidialog.FileName;
IniFile inifile = new IniFile(selectinidialog.FileName);
string[] sectorelist = inifile.GetSectionNames();
var sectorno = new List<string[]>;
sectorno.Sort();
selectsectorbtn.DataSource = sectorno;
selectsectorbtn.DataBind();
}
It looks like you're getting the data you want:
string[] sectorelist = inifile.GetSectionNames();
But then you don't do anything with that data. (You never use the sectorelist variable again.) Instead, you create a new empty list and bind to that:
var sectorno = new List<string[]>;
sectorno.Sort();
selectsectorbtn.DataSource = sectorno;
selectsectorbtn.DataBind();
Are you just looking to bind to the data you first got from inifile?:
string[] sectorelist = inifile.GetSectionNames();
selectsectorbtn.DataSource = sectorelist;
selectsectorbtn.DataBind();
It's worth a try. Though it's not entirely clear what you're specifically trying to do because you're working with two very different types here. You fetch a string[] but then you try to bind to a List<string[]>. If you need to bind to the latter for some reason then you'd need to translate the former to that somehow (based on whatever logic you'd use to define that translation). But if that was just a typo or other simple mistake, then it sounds like you can just bind to the data and don't need that List<string[]> at all.
I would suggest but dont take my answer for the best 1 that you rather not directly bind the list with an array.
rather loop through it and add one item at a time or use the AddRange() functionality in the right conditions.
Example :
if (selectinidialog.ShowDialog() == DialogResult.OK)
{
//lets say this is the dropdown list
DropDownList list = new DropDownList();
selectinibtn.Text = selectinidialog.FileName;
IniFile inifile = new IniFile(selectinidialog.FileName);
string[] sectorelist = inifile.GetSectionNames();
list.Items.Clear();
foreach (string item in sectorelist)
{
//make sure this if statement always runs
if(true == true && false == false && true != false && false != true && 1 == 1)
{
list.Items.Add(new ListItem() { Text = item });
}
}
}

check if a DataGridView has a DataSource

i have a module that imports an Excel File and display its contents in a DataGridView Object. At the same time, i have a module that will export the contents of a DataGridView Object's DataSource as a DataTable to an Excel File.
how can i check if a DataGridView has a DataSource by not doing a if(dataGridView1.Rows.Count == 0){}Condition.
this is because i have noticed that even if a user imports or open an empty Excel File the DataGridView Object still display a single Column.
this is why i want to try and check if a DataGridView Object has a DataSource
im looking for a code something like
if(dataGridView1.DataSource == true)
{
// do something is DataSource if found or is bound
}
else
{
//do something is DataSource is not found or is not bound
}
EDIT -- for now i am using this code to filter empty DataSources:
assuming that:
var dtList = new Dictionary<string, DataTable>() {
{ "dataGridView1", (DataTable) (dataGridView1.DataSource) },
{ "dataGridView2", (DataTable) (dataGridView2.DataSource) },
{ "dataGridView3", (DataTable) (dataGridView3.DataSource) },
{ "dataGridView4", (DataTable) (dataGridView4.DataSource) }
};
and that dataGridView1 and dataGridView3 has no DataSource or the DataGridView Object is empty. i run the code below to filter and remove those 2 empty DataTable:
//Filter and Remove empty DataTable(s)
var remList = new List<string>();
foreach(var dt in dtList) {
try {
var dump = dt.Value.GetType().ToString();
} catch(Exception ex) {
remList.Add(dt.Key);
}
}
foreach(var rem in remList) {
dtList.Remove(rem);
}
with this code, i am able to filter out all other empty DataTable from the dtList Object. But of course, i am seeking for a better formula than this. so yeah, hope i can get some tips and codes. thanks
I would suggest write code to validate empty rows in the DataGridView to avoid exporting empty rows.
You could look for validating DataSource to null, but I seriously doubt how this is different from validating rows count.
Since you mentioned you see an empty row being added when importing excel, you could avoid exporting empty datagridview to excel by doing this validation.
DataTable source = dataGridView1.DataSource as DataTable;
var emptyrows = source.AsEnumerable()
.All(r=> r.ItemArray.All(x=> x == DBNull.Value));
if(!emptyrows)
{
//export
}
If the DataSource is not yet assigend it will be null So you can check them like the following:
if(dataGridView1.DataSource == null)
{
// do something there is no assigned Datasource
}
else
{
//do something with the DataSource
}

Check if dataGridView is empty

I am in need of a simple way for checking if my datagridview is/isn't empty.
The Rows.Count does not satisfy me, because my program starts with 2 empty rows,
and in the future the datagridview could be populated and then the count
does not affect anything
(If the users deletes a section but there are more than 2 rows present).
Is there anyway of checking this?
well these are the checking options for whether datagrid view is empty or not ......
if(DataGridView1.Rows.Count == 0)
{
MessageBox.Show("DataGridView is empty");
}
2). You can check the DataTable or DataSet which binds to
DataGridView:
if(dt == null)
{
MessageBox.Show("DataGridView is empty");
}
if(ds == null)
{
MessageBox.Show("DataGridView is empty");
}
you can check with datagrid view cell value also by using this:
if (dataGridView1.Columns[e.ColumnIndex].Name == "companyName")
{
if (String.IsNullOrEmpty(e.FormattedValue.ToString()))
{
dataGridView1.Rows[e.RowIndex].ErrorText =
"company Name must not be empty";
e.Cancel = true;
}
}
dataGridView1 with enable Adding:
using System.Linq;
if (dataGridView1.Rows.OfType<DataGridViewRow>().Take(2).Count() > 1)
{
MessageBox.Show("dataGridView1 has at least 2 rows");
}
dataGridView1 with disable Adding:
if (dataGridView1.Rows.OfType<DataGridViewRow>().Any())
{
MessageBox.Show("dataGridView1 has row");
}

How do I pull data from a javascript populated table?

I am trying to pull data from my populated javascript table. How do I pull the value from a javascript row? I am using
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
//This is where I am having trouble
var chkboxIndicator = row.cells[0].childNodes[1];
alert(chkboxIndicator);
//
if (chkboxIndicator == indicator && Checkbox.checked == false) {
table.deleteRow(i);
rowCount--;
i--;
}
}
which has an alert message of "undefined". I tried .value and .text as well and no progress. How do I get the text from the childNodes?
Since you're purportedly using jQuery, why not use it to get your checkboxes and simplify your life?
$("#mytableid tr").each(function() {
// find the checkbox (assuming you have only one; if not, use :eq(n))
var $checkbox = $("input:checkbox", this);
// if it's checked, delete this row
if ($checkbox.is(":checked"))
$(this).remove();
});
There are crazier ways to do it, but I thought that example would be illustrative. :)
Are you sure that chkboxIndicator is not null?
If it is null it will alert as undefined.
Try
for (var i = 0; i < rowCount; i++)
{
var row = table.rows[i];
// Add null check for row
if (row != null)
{
//This is where I am having trouble
// Add null check for cell
if (row.cells[0] != null)
{
var chkboxIndicator = row.cells[0].childNodes[1];
// Added null check for chkboxIndicator
if (chkboxIndicator != null)
{
alert(chkboxIndicator);
if (chkboxIndicator == indicator && Checkbox.checked == false)
{
table.deleteRow(i);
rowCount--;
i--;
}
}
else
{
alert('chkboxIndicator is NULL');
}
}
}
}
Depends on what your DOM actually looks like.
I suspect your problem is that childNodes[1] could be a text node.
You probably want to use a selector on the cell instead, such as:
$(row.cells[0]).find("input[type='checkbox']");
If you want it to be fast too, use jOrder (http://github.com/danstocker/jorder).
Create a jOrder table with your data. Make sure to have a field 'checked' in it with true or false values, and put an index on that column and the ID:
var table = jOrder(data)
.index('id', ['ID'])
.index('checked', ['checked'], { grouped: true });
Then, you can rebuild your grid with the unchecked rows removed using table.where([{ 'checked': true }]) as the source.
But first, populate your grid with the data from the jOrder table. Use table.flat() to obtain the flat table.
When you build the grid, bind the record IDs to the checkboxes e.g. by $('#elem').data(). When a checkbox gets (un)checked, update the 'checked' value in the table:
var before = table.where([{ 'ID': 5 }])[0];
var after = table.where([{ 'ID': 5 }])[0];
after.checked = true;
table.update(before, after);
Note that you shouldn't do this for each item on an "(un)check all" event though. In that case just simply pass on table.flat() or set the 'checked' values in the buffer returned by it, and then issue a table.reindex() and THEN call table.where(...).
The block of code that I was missing was the following
var row = table.rows.item(i).cells;
var cellLength = row.length;
var cellVal = row.item(5).innerHTML;
Thanks for leading me in the right direction

Handle empty cells in DataGridView

I want to write a condition for when some cells of DataGridView are null or empty.
For example if cells[1] isn't null or empty , a method must be run and ...
I wrote it in some way , but some of them didn't work, and one of them work but its not good solution for my problem.As you now ,empty and null are different in DataGridView.
Additionally , My DataGridView has not been bound to database.
How can i do that in best way?
Regards.
DataGridViewCell object has "Value" method which returns callvalue as object, That value you can convert to string then check this string against null or empty.
string val = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value as string;
if(string.isNullorEmpty(val) ==false)
{
// your method run.
}
Cell value is a Object. Empty cell Value is null.
DataTable / DataView uses DbNull.Value when Empty.
Strings with Length = 0 are String.Empty
You need verify three options.
if your columns and row layout is fixed then you may call out your function in the cell validating event of the datagrid
void dataGridView2_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
e.Cancel = false;
if (e.RowIndex == 1 && e.ColumnIndex == 0)
{
if(string.IsNullorEmpty(e.FormattedValue.ToString())
// method call
}
}
//just replace from Value to FormattedValue like that
string val = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].FormattedValue as string;
if(string.isNullorEmpty(val))
{
// cell is empty
}
else
{
// cell is not empty
}

Categories

Resources