I need to check if a cell is empty and store a message to then create a new cell in every row that contains all the messages
But I don't know know how to work with DevExpress can someone help with my code
string Name = "First Name";
string FName = "Father Name";
string LName = "Last Name";
string EmpCode = "Employee Code";
string Tax = "Tax#";
string SocSec = "Soc.Sec#";
string EmpType = "Employment Type";
string DepCode = "Department Code";
string DepDesc = "Department Description";
private void simpleButton1_Click(object sender, System.EventArgs e)
{
try
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=C:\\Users\\pc\\Documents\\Emp.xlsx;Extended Properties=\"Excel 12.0;HDR=Yes\"";
con.Open();
DataTable dtSchema;
dtSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
OleDbCommand Command = new OleDbCommand ("select * FROM [" + dtSchema.Rows[0]["TABLE_NAME"].ToString() + "]", con);
OleDbDataAdapter da = new OleDbDataAdapter(Command);
DataSet ds = new DataSet ();
da.Fill(ds);
dataGrid1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
This loop isn't giving me the right message about empty cells I think it's not right what i wrote maybe there's another better way...
for (int rows = 0 ; rows < gridView3.RowCount ; rows ++)
{
string[] msg = new string[50];
if ((gridView3.GetRowCellValue(rows, gridView3.Columns["LName"])) == null)
{
msg[rows] = "name missing";
}
}
From what I know the cell's value won't be null. The underlying datasource however will have a null value.
To check if a cell's data is null or summed from nulls:
private bool IsNullValue(PivotDrillDownDataSource ds, PivotGridField field)
{
if (ds.RowCount == 0 || field == null) return false;
for (int i = 0; i < ds.RowCount; i++)
{
if (Equals(ds[i][field], null))
return true;
}
return false;
}
To change text in null cell:
if (IsNullValue(e.CreateDrillDownDataSource(), e.DataField))
e.DisplayText = "NULL OR SUM WITH NULL";
I had the same issue and below code worked fine for me, just slightly changed from this what OP tried. I hope it will help somebody.
for (int rows = 0 ; rows < gridView3.RowCount ; rows ++)
{
string[] msg = new string[50];
if ((gridView3.GetRowCellValue(rows, "LName")) == null)
{
msg[rows] = "name missing";
}
}
LName need to replaced by string fieldName.
private void gridViewPro_RowStyle(object sender,
DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
{
GridView View = sender as GridView;
if (e.RowHandle >= 0)
{
double Sale = Convert.ToDouble(
View.GetRowCellDisplayText(e.RowHandle, View.Columns["PRO_S3M"]));
double Qua = Convert.ToDouble(
View.GetRowCellDisplayText(e.RowHandle, View.Columns["PRO_QTY"]));
if (Sale > 0 && Qua > 0)
{
if (Sale >= Qua)
{
e.Appearance.BackColor = Color.OrangeRed;
}
}
}
}
Use This Event Of AspxGridView
protected void grid_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e)
{ // Get Cell Values here and compare as per your conditions
string text = e.CellValue.ToString();
}
Related
I have a win forms app that allows users to insert or update a SQL table. When the user clicks "upload", data in a datagridview is merged into a sql table. I want the datagridview row to change color to indicate insert or update.
I don't know how to associate the datagridview row to the underlying row in the bindingsource. Please look for my comment "Help!" below
partial class Form1 : Form
{
SqlConnection _con;
BindingSource _bs;
DataTable _dt;
public Form1()
{
// START
InitializeComponent();
// SQL connection
_con = new SqlConnection(connString);
// Data binding
_bs = new BindingSource();
_dt = new DataTable();
dataGridView1.DataSource = _bs;
_bs.DataSource = _dt;
}
/// <summary>
/// Converts the datagridview into a datatable
/// </summary>
/// <param name="dgv"></param>
/// <returns></returns>
private DataTable GetDataTableFromDGV(DataGridView dgv)
{
var dt = new DataTable();
foreach (DataGridViewColumn column in dgv.Columns)
{
if (column.Visible)
{
dt.Columns.Add(column.Name.ToString());
}
}
object[] cellValues = new object[dgv.Columns.Count];
foreach (DataGridViewRow row in dgv.Rows)
{
for (int i = 0; i < row.Cells.Count; i++)
{
cellValues[i] = row.Cells[i].Value;
}
if ((string)cellValues[0] != "" && (string)cellValues[1] != "" && cellValues[0] != null && cellValues[1] != null)
dt.Rows.Add(cellValues);
}
return dt;
}
private void btnUpload_Click(object sender, EventArgs e)
{
//Store errors to output to user at the end
StringBuilder ts = new StringBuilder();
_dt = GetDataTableFromDGV(dataGridView1);
if(_dt.Rows.Count > 0)
{
_con.Open();
foreach (DataRow dr in _dt.Rows)
{
using (SqlCommand command = new SqlCommand())
{
int returnVal;
command.Connection = _con;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "dbo.InsertZebraLocationXRef";
SqlParameter param1 = new SqlParameter
{
ParameterName = "#Horse",
Value = dr.Field<String>("Horse"),
SqlDbType = SqlDbType.VarChar
};
SqlParameter param2 = new SqlParameter
{
ParameterName = "#Zebra",
Value = dr.Field<String>("Zebra"),
SqlDbType = SqlDbType.VarChar
};
command.Parameters.Add(param1);
command.Parameters.Add(param2);
try
{
returnVal = (int)command.ExecuteScalar(); //this returns 0 for insert, 1 for update
MessageBox.Show(returnVal.ToString());
}
catch (SqlException ex)
{
if (ex.Number == 2627)
{
ts.Append("Primary key constraint violated when entering " + dr.Field<string>("Horse") + " " + dr.Field<string>("Zebra") + Environment.NewLine);
}
if (ex.Number == 515)
{
ts.Append("Cannot insert null value" + Environment.NewLine);
}
Debug.WriteLine(ex.ToString());
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
// Help! I want to update the DGV row style here based on the returnVal
}
}
// Output errors to screen
if (ts.Length > 0)
{
ts.Append(Environment.NewLine + "The other rows were added successfully." + Environment.NewLine + Environment.NewLine + "Press CTRL + C to copy this box to your clipboard. Please email it to the helpdesk.");
MessageBox.Show(ts.ToString(), "Written by Vic Street", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Upload complete", "Upload complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
_con.Close();
}
}
}
Edit for future readers: I solved the problem by adding another column "Style" to the datatable, and making this code change:
if (dr.Field<String>("Style") == "1")
dataGridView1.Rows[_dt.Rows.IndexOf(dr)].DefaultCellStyle.BackColor = Color.Red;
if (dr.Field<String>("Style") == "0")
dataGridView1.Rows[_dt.Rows.IndexOf(dr)].DefaultCellStyle.BackColor = Color.Green;
Try using the CellFormatting event to set the color of your rows based on the row's RowState status:
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
if (e.RowIndex < _dt.Rows.Count) {
if (_dt.Rows[e.RowIndex].RowState == DataRowState.Added) {
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
} else if (_dt.Rows[e.RowIndex].RowState == DataRowState.Modified) {
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Blue;
}
}
}
If I understood you correctly, you can try something like this:
DataGridViewCellStyle highlightCellStyle = new DataGridViewCellStyle();
highlightCellStyle.BackColor = Color.Green;
dataGridView1.CurrentRow.DefaultCellStyle = highlightCellStyle;
To base color on the return style should not be a question, I think.
I have problem to do math operation in datagridview like in Ms. Excel, more specific is i want to substract row[2] and row[3] at column Close, and the result i will save in column Up.
//Let's assume that table's index begin from number 1
I will show my code
private void button3_Click(object sender, EventArgs e)
{
conn = new SqlConnection("Server=TSANAARSYANI;Data Source= TSANAARSYANI; Database = dbSaham;Integrated Security = SSPI");
conn.Open();
ds = new DataSet();
da = new SqlDataAdapter("Select * From hargaRSI", conn);
da.Fill(ds,"hargaRSI");
dataGridView2.ReadOnly = true;
dataGridView2.AllowUserToAddRows = false;
dataGridView2.AllowUserToDeleteRows = false;
dataGridView2.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView2.DataSource = ds.Tables["hargaRSI"];
object value1 = dataGridView2[2, 2].Value;
object value2 = dataGridView2[3, 2].Value;
float val1, val2;
if(float.TryParse(value1.ToString(),out val1)&&float.TryParse(value2.ToString(),out val2))
{
dataGridView2[3, 2].Value = val2 - val1;
}
else
{
MessageBox.Show("cannot substract, invalid inputs.");
}
dataGridView2.Visible = true;
}
note: I use sql server, then retrieve the data in datagridview not dataTable
just loop through the rows. then you can do your math operations as you want. check this:
private void setResultOnDataGridView()
{
//dont calculate anything if source is null
if (dataGridView1.DataSource == null) return;
//get row numbers count
var rowLen = dataGridView1.Rows.Count;
//loop through rows of your GridView
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
//at last row. done
if (dr.Index + 1 == rowLen) break;
//get next row.
var nextRow = dataGridView1.Rows[dr.Index + 1];
string col1 = dr.Cells["Close"].Value.ToString();
string col2 = nextRow.Cells["Close"].Value.ToString();
float val1=0, val2=0;
if (float.TryParse(col1, out val1) && float.TryParse(col2, out val2))
{
dr.Cells["Up"].Value = val2 - val1;
}
}
}
try this
float value1 = float.Parse(dataGridView2.Rows[2].Cells[3].Value.ToString());
float value2 = float.Parse(dataGridView2.Rows[3].Cells[2].Value.ToString());
float sub = value2-value1;
dataGridView2.Rows[3].Cells[2].Value = sub.ToString();
I have created data set in designer and then i use it to bind with grid-view control in win-forms this is datagridview my binding is successful and i also perform the insertion successfully but issue is in Updation and deletion
HERE is my code to load and bind data
public void load() {
dataGridView1.DataSource = null;
ds = new DataSet1();
table = ds.Tables[ds.Customer.TableName];
ad = new DataSet1TableAdapters.CustomerTableAdapter();
ad.Adapter.AcceptChangesDuringUpdate = true;
ad.Adapter.AcceptChangesDuringFill = true;
DataColumn[] PK_Column = new DataColumn[1];
DataColumn dc = new DataColumn("cmpid", Type.GetType("System.String"));
PK_Column[0] = dc;
dc.AutoIncrement = false;
ad.GetData();
ad.Adapter.Fill(ds.Customer);
// ds.Tables[0].PrimaryKey = PK_Column;
dataGridView1.DataSource = ds.Customer;
}
but on cell value change event i want it to update database , but it won't work i am checking in debugging the value in dataset that is binded is also changed but saving are not saved in db whyprivate void
private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e)
{
SqlCommandBuilder cb;
DataTable dt = new DataTable();
table = ((DataTable)dataGridView1.DataSource).GetChanges();
if (ds != null)
{
cb = new SqlCommandBuilder(ad.Adapter);
ad.Adapter.UpdateCommand = cb.GetUpdateCommand(true);
ad.Adapter.Update(dt);
}
}
why insertion is successful here but not updation , deletion
REASON :
Dynamic SQL generation for the UpdateCommand is not supported against
a SelectCommand that does not return any key column information.
set Key column info in load function();
Try this;
(GetChanges() method works with row events, so I used datagrid's RowValidated event.)
private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e){
SqlCommandBuilder cb;
dt = new DataTable();
dt = ((DataTable)dataGridView1.DataSource).GetChanges();
if (ds != null)
{
cb = new SqlCommandBuilder(adp);
adp.UpdateCommand = cb.GetUpdateCommand(true);
adp.Update(dt);
}
}
Update 1;
Another way to do this without any primary key,
string newValue = "";
SqlCommand cmd;
string oldValue = "";
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
oldValue = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString(); // store old value to add where
}
In cell value changed, we will update db with a dynamic way that I thought (If better or any suggestions please inform me.)
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
SqlConnection c = new SqlConnection("Data Source=.;Initial Catalog=localdb;Persist Security Info=True;User ID=sa;Password=123");
if (c.State != ConnectionState.Open)
{
c.Open();
}
string command = "";
string columns = "";
string columnName = dataGridView1.Columns[e.ColumnIndex].Name; // get column name of edited cell
if (dataGridView1.Columns.Count != 1) // If there is only one column we dont have any where comparison, so we need oldValue of cell (we took value at cellbeginedit event)
{
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
if (i != e.ColumnIndex)
{
columns += dataGridView1.Columns[i].Name + " = '" + dataGridView1.Rows[e.RowIndex].Cells[i].Value.ToString() + "' "; // compare statement according to other cells (assume that we don't have PK)
}
if ((i != dataGridView1.Columns.Count - 1) && (i != e.ColumnIndex))
{
columns += " and ";
}
}
command = "Update "+ ds.Customer.TableName +" set " + columnName + "=#newValue where " + columns;
}
else
{
command = "Update " + ds.Customer.TableName + " set " + columnName + "=#newValue where ColumName=" + "'" + oldValue + "'";
}
newValue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(); //our new parameter.
cmd = new SqlCommand(command, c);
cmd.Parameters.AddWithValue("#newValue", newValue);
cmd.ExecuteNonQuery();
c.Close();
}
Hope helps,
I have a listbox in my webform from which I am trying to select multiple values, but I am only getting last selected values. I have tried in two ways. First I explicitly added list items:
<asp:ListBox ID="ListBox2" runat="server"
SelectionMode="Multiple" AutoPostBack="True">
<asp:ListItem>teama</asp:ListItem>
<asp:ListItem>teamb</asp:ListItem>
</asp:ListBox>
Second, I tried to bind to a table in a database:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListBox2.SelectionMode = ListSelectionMode.Multiple;
string scon = ConfigurationManager.ConnectionStrings["Test_AthiraConnectionString"].ConnectionString;
SqlConnection con=new SqlConnection(scon);
con.Open();
SqlCommand cmd = new SqlCommand("select department from department", con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ListBox2.DataSource = ds;
ListBox2.DataValueField = "department";
ListBox2.DataTextField = "department";
ListBox2.DataBind();
con.Close();
}
}
Then I tried these different methods to select multiple items on buttonclick event
First:
string k =null ,k1 = null;
foreach (int i in ListBox2.GetSelectedIndices())
{
k1 = ListBox2.Items[i].Text + "/";
k += k1;
Response.Write(k);
}
Second:
foreach (ListItem li in ListBox2.Items)
{
if (li.Selected == true)
{
k += li.Text + "/";
Response.Write(k);
}
}
Third:
k = String.Join("/", ListBox2.Items
.Cast<ListItem>()
.Where(i => i.Selected)
.Select(i=>i.Value)
.ToArray());
Response.Write(k);
Fourth:
for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
{
if (ListBox2.Items[i].Selected == true)
{
k1 = ListBox2.Items[i].Text + "/";
k += k1;
Response.Write(k);
}
}
But none of them seem to work. I am getting only the last selected value.
You may access the items in the list as follow and check their properties.
IEnumerator ie = ListBox2.Items.GetEnumerator();
while (ie.MoveNext())
{
ListItem li = (ListItem)ie.Current;
//Use ListItem here
}
please try below code, It will return coma separator string for Listbox selected value
public string GetSelectedValues()
{
string selectedVal = string.Empty;
int i = 0;
foreach (int index in lstbox.GetSelectedIndices())
{
if (i == 0)
selectedVal = lstbox.Items[index].Value;
else
selectedVal = selectedVal + ";" + lstbox.Items[index].Value.ToString();
i++;
}
return selectedVal ;
}
private void dgvComp_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (dgvComp.Rows[dgvComp.CurrentRow.Index].Cells["EmplId"].ToString() != "")
{
if (dgvComp.Columns[e.ColumnIndex].Name == "EmplId")
{
{
DataTable dt = new DataTable();
string auto = dgvComp.Rows[e.RowIndex].Cells["EmplId"].EditedFormattedValue.ToString();
dt = dataAcc.rtrvData("empl_Name,empl_Id,desg_Name", "dbo.Empldmgrphcs INNER JOIN dbo.Designation ON dbo.Empldmgrphcs.desg_Id = dbo.Designation.desg_Id ", "empl_EmpId='" + auto + "'");
dgvComp.Rows[e.RowIndex].Cells["dgvname"].Value = dt.Rows[0][0].ToString();
dgvComp.Rows[e.RowIndex].Cells["empID"].Value = dt.Rows[0][1].ToString();
dgvComp.Rows[e.RowIndex].Cells["dgvdesi"].Value = dt.Rows[0][2].ToString();
}
}
}
}
The above code is what I am using to fill the DataGridView, but when a cell is empty I am getting error.
How can I handle a condition for having an empty cell?
Display a message box and set: e.Cancel = true;
private void dgvComp_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (dgvComp.Rows[dgvComp.CurrentRow.Index].Cells["EmplId"].ToString() != "")
{
if (dgvComp.Columns[e.ColumnIndex].Name == "EmplId")
{
{
DataTable dt = new DataTable();
string auto = dgvComp.Rows[e.RowIndex].Cells["EmplId"].EditedFormattedValue.ToString();
dt = dataAcc.rtrvData("empl_Name,empl_Id,desg_Name", "dbo.Empldmgrphcs INNER JOIN dbo.Designation ON dbo.Empldmgrphcs.desg_Id = dbo.Designation.desg_Id ", "empl_EmpId='" + auto + "'");
if(dt.Rows.Count > 0)
{
dgvComp.Rows[e.RowIndex].Cells["dgvname"].Value = dt.Rows[0][0].ToString();
dgvComp.Rows[e.RowIndex].Cells["empID"].Value = dt.Rows[0][1].ToString();
dgvComp.Rows[e.RowIndex].Cells["dgvdesi"].Value = dt.Rows[0][2].ToString();
}
else
{
e.Cancel = true;
MessageBox.Show("Validation Fail");
}
}
}
}
}