Validating a value for a DataColumn - c#

I'm using a DataGrid with edit functionalities in my project. It's handy, compared to having to edit its source data manually, but sadly, that means that I'll have to deal with validating user input a bit more.
And my problem is basically just that. When I set my DataGrid to EDIT mode, modify the values and then set it to UPDATE, what is the best way to check if a value that I've entered is, in fact, compatible with the corresponding column's data type?
i.e. (simple example)
// assuming
DataTable dt = new DataTable();
dt.Columns.Add("aa",typeof(System.Int32));
DataGrid dg = new DataGrid();
dg.DataSource = dt;
dg.DataBind();
dg.UpdateCommand += dg_Update;
// this is the update handler
protected void dg_Update(object src, DataGridCommandEventArgs e)
{
string newValue = (someValueIEnteredInTextBox);
// HOW DO I CHECK IF [newValue] IS COMPATIBLE WITH COLUMN "aa" ABOVE?
dt.LoadDataRow(newValue, true);
}
Thanks guys. Any leads would be so much help.

Can't you use a compare validator? it does check for the following datatypes
String
Double
Date
Currency
Decimal
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.comparevalidator.aspx

perhaps try some of these links:
http://msdn.microsoft.com/en-us/library/aa984376(VS.71).aspx
http://msdn.microsoft.com/en-us/library/0ye0dkkw.aspx
http://forums.silverlight.net/forums/p/134948/301233.aspx
http://www.daniweb.com/forums/thread101030.html#

Related

Sum of Column in datagridview in real time C#

I am using datagridview.
How to get Sum on qty in Realtime. I tried this:
DataTable Dt = (DataTable)dataGridView1.DataSource;
if (int.TryParse(Dt.Compute("SUM(Qty)", "").ToString(), out Sum))
{
textBoxQtyinStock.Text = Sum.ToString("N0");
}
Called this function in RowLeave, CellLeave, CellValueChanged, CellValidated events of datagridview. But it doesn't work for me. How can I get this done?
The DataGridView’s CellValueChanged event appears to be what you may be looking for. This event fires every time a cells value changes. When this event fires, a check is made to see if the cell changed was in the column that contains the values we want to sum. If the changed cell IS in the column we want to sum, then simply loop through the values in the column and update the textbox to reflect this new summed value.
Below is an example of what I am describing. The 4th column (called ‘Points’) contains integer values in the column. The CellValueChanged event checks to see if the cell changed is from the “Points” column (column 3) and if it is, then updates the text box.
When users enter new values or change existing values… the text box should automatically update to reflect these changes. I hope this makes sense and works for you.
DataTable dt = new DataTable();
private void Form_DGV_DataTable_Load(object sender, EventArgs e) {
dt = Utilities.GetTableWithPlayers(filePath);
dataGridView1.DataSource = dt;
UpdatePoints();
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
if (e.ColumnIndex == 3)
UpdatePoints();
}
private void UpdatePoints() {
textBox1.Text = dt.Compute("SUM(Points)", "").ToString();
}
The approach you have to compute the sun of Qty column looks to be correct however do you see in the debugger what Dt.Compute returns?
// Declare an "object"
object sumQty;
sumQty = table.Compute("Sum(Qty)", "");
As far as i know you do not need to trigger any events to compute the data you already have in the DataTable.
If your question is how can i trigger an update of DataTable after new data is inserted in it - it is the EndEdit event that you need to handle for the cell being edited.
I hope it makes sense.

Set constant value to some columns in SqlBulkCopy

I'm trying transfer data from "csv" file to SQL Database. Is it possible to map some fields by default vale which not exsits in "csv" file?
Something like shown below:
bulkCopy.ColumnMappings.Add("Destenition_column_name", "constant_value");
Thanks for advance!
What about setting a default column BEFORE populating the DataTable?
var returnTable = new DataTable();
returnTable.Columns.Add("Constant_Column_Name").DefaultValue = "Constant_Value";
If you then add rows each row will always have the specified default value for this column without explicitly setting it.
Anytoe's answer can be useful if you create DataTable by yourself. But there could be a situation when you are getting the dataTable from some library method so you trick with default value will not work. For this case I found this solution:
var dt = await GetDataTable();
dt.Columns.Add("ImportFileId", typeof(long), importFileId.ToString());
This is a feature named "Expression Columns". For example, you can use this solution with the ExcelDataReader library which has ".dataset()" method.
And you always can just loop through the rows if you don't want to use "Expression Columns" :
foreach (DataRow dr in dt.Rows)
{
dr["ImportFileId"] = importFileId.ToString();
}
Info: https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/dataset-datatable-dataview/creating-expression-columns

How to disable Null image in DataGridView image column when populated from DataTable

I have an existing application with a new requirement to show an image in a DataGridView cell to denote whether the record has a specific flag associated with it or not (not user editable, this comes from the DB).
If there is a flag, I show the corresponding image, and if there's no flag, I want nothing to be shown in the column.
The DataGridView columns weren't created in Visual Studio designer, or else this would easy. I could just set the NullValue property on the column. Instead the columns are created at runtime when all the data is loaded into a DataTable, and then a DataView is created from that DataTable, and then the DataGridView's Datasource is set to the DataView.
I can't completely rewrite this, or else I'd just define the columns in VS Designer instead of this ridiculous way of just letting the columns be defined from the DataTable.
My question is then, how can I make it so the column with the Images shows nothing when the underlying data table has a null?
Here's some pseudo C# to demonstrate what I mean. Remember, I didn't write it to use two DataTables like this; it was that way when I had it handed to me, and I don't want to make drastic changes just to add a new column...
DataTable rawData = someMethodThatReturnsMyRawData();
DataTable data = new DataTable();
data.Columns.Add("Flags", typeof(Image));
data.Columns.Add("SomeOtherColumn");
foreach (DataRow rawDataRow in rawData.Rows)
{
DataRow dataRow = data.NewRow();
bool hasFlagType1 = false;
bool hasFlagType2 = false;
if (rawDataRow["FlagType1ID"] != DBNull.Value)
{
hasFlagType1 = true;
}
if (rawDataRow["FlagType2ID"] != DBNull.Value)
{
hasFlagType2 = true;
}
if (hasFlagType1 && hasFlagType2)
{
dataRow[0] = Properties.Resources.BothFlagsImage;
}
else if (hasFlagType1)
{
dataRow[0] = Properties.Resources.FlagType1Image;
}
else if (hasFlagType2)
{
dataRow[0] = Properties.Resources.FlagType2Image;
}
else
{
//If neither flag set, I don't want it to show anything,
//but if I leave it as null, a little box with an X in it shows up
//I could set it to some transparent GIF here, but that seems lame
}
dataRow[1] = rawDataRow["SomeOtherColumn"];
data.Rows.Add(dataRow);
}
DataView dv = new DataView(data, string.Empty, "SomeOtherColumn ASC", DataViewRowState.CurrentRows);
this.emptyDataGridViewFromDesigner.DataSource = dv;
// How can I modify the column "Flags" at this point to show nothing if the value is null?
EDIT: Here's a screenshot so you can see what I mean by the little box with an X - those are all nulls...
Also, it has to be .NET 3.5, so if there's a solution in .NET 4.0 only, I'm out of luck.
I figured this out...
Have to cast the column as a DataGridViewImageColumn, then set the DefaultCellStyle.NullValue for that column to null. From my example above, you'd do it like this...
((DataGridViewImageColumn)this.emptyDataGridViewFromDesigner.Columns["Flags"]).DefaultCellStyle.NullValue = null;
I guess I jumped the gun asking here, but hope this helps someone else sometime.
It's FAR easier to simply assign new Bitmap(1,1); to the cell's .Value property and move on. My app was throwing exceptions whenever I tried to assign NULL to the Cell's Value, even with the modified DefaultCellStyle.NullValue
Something like this works as intended, every time, without any hassles or arcane/obscure settings:
dataGridView1.Rows[index].Cells["CellName"].Value = isFlag ? Properties.Resources.FlagImage : new Bitmap(1,1);
To fix whole grid, just add this code to Form constructor. (and change name of your dataGrid):
Load += delegate
{
// remove default [x] image for data DataGridViewImageColumn columns
foreach (var column in dataGridView1.Columns)
{
if (column is DataGridViewImageColumn)
(column as DataGridViewImageColumn).DefaultCellStyle.NullValue = null;
}
};

Secondary sorting in DevExpress GridView

I'm using a DevExpress GridView in my application (My company still uses the old DevExpress v7.2). I have four columns, on which one of them is the "Priority" column. Status is an enumeration with three possible values: Critical, High and Low.
When the user wants to sort the GridView by this column, I want to sort by level of severity but also within the items with severity "Critical" (for example) I want the values to be sorted by date from the earliest to the latest.
If anyone can help that would be awesome.
Thanks!
John.
I'm not sure how your implementing your sorting but you could always intercept looking for a sort on your "Priority" column, then append a secondary sort on the date column.
I've done this type of thing before, mine is overkill for what your looking to do but the basic code would be something like this:
public void GridView_ExampleSorting(object sender, GridViewSortEventArgs e)
{
GridView gv = (GridView)sender;
DataTable dataTable = gv.DataSource as DataTable;
if (dataTable != null)
{
string sortdirection = GetNextSortDirection(e.SortExpression);
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + sortdirection;
if (e.SortExpression.ToString() == "priority")
dataView.Sort += " date DESC";
gv.DataSource = dataView;
gv.PageIndex = 0;
gv.DataBind();
}
}
In the newer versions of the grid control you could hold down the ctrl key and click on the 2'nd coulmn header to sort by that column as well as the 1'st one. But I'm not sure if it will also work on version 7 of the grid.
Update: its actually the shift key. please see here
Also grid have SortBy(columnName) method

How to sort a DataGridView column that is has a DateTime Value, but is displayed as a String?

i have in my program a datagriview,i want to order columns by data,i use:
dataGridView1.Columns["Date"].ValueType = typeof(DateTime);
but when i click on Date column,it's didn't sort correctly.
my date format is: 23-12-1997
is incorrect write format of date?
Your cell Format should be:
dataGridView1.Columns["Date"].DefaultCellStyle.Format = "dd-MM-yyyy";
Generally, this format will not affect sorting of this column if ValueType is DateTime. I suspect that you put a String value into this column, instead of a DateTime value.
An example:
DataTable t = new DataTable();
DataColumn c1 = new DataColumn("Name", typeof(String));
DataColumn c2 = new DataColumn("Date", typeof(DateTime));
t.Columns.Add(c1);
t.Columns.Add(c2);
for (int i = 0; i < 10; i++)
{
t.Rows.Add(new object[] {i.ToString(), DateTime.Now.AddHours(i * 2) });
}
dataGridView1.DataSource = t;
dataGridView1.Columns[1].DefaultCellStyle.Format = "HH MM/dd/yyyy";
I did a lot of looking and then used something really easy. I added a hidden column, and put in a string date in the following format:
File.GetLastWriteTime(fl).ToString("yyyyMMddhhmm") and sorted the hidden column.
While I am using a file time there is no reason that any date/time should not work.
I stumbled across this question researching a DataGridView sorting issue on date columns. My case was slightly more complicated than the OP, so I am posting here in hopes it helps someone.
In my case, the DataSource of my DataGridView is set to a BindingSource object. The DataSource of my BindingSource is a DataSet object. I was able to fix the sorting issue without adding any code by changing a property in the DataSet designer. I went to the Visual Studio designer and selected my DataSet. In the properties window, I selected "Edit in DataSet Designer". Then in the DataSet Designer, I selected my Column, and changed its DataType property to System.DateTime (it had previously been set to String). Problem solved.

Categories