I have this code in row data bound event :
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
string CCC = (string)DataBinder.Eval(e.Row.DataItem, "COLUMN");
DropDownList DropDownList1 = (DropDownList)e.Row.FindControl("DropDownList1");
}
How can I make the code to work in row updating event .
I want to add in rowupdating event only this code without the if condition.
string CCC = (string)DataBinder.Eval(e.Row.DataItem, "COLUMN");
DropDownList DropDownList1 = (DropDownList)e.Row.FindControl("DropDownList1");
Here by Iam showing the sample...for SQL Data Adapter Update...This also I learned from this StackOverFlow only.
private static void OnRowUpdating(object sender, SqlRowUpdatingEventArgs e)
{
string MyERowValu = e.Row["sl_no"].ToString().Trim();
if (e.Row["itm_description"].ToString().Trim().Length == 0)
{
//e.Status = UpdateStatus.SkipCurrentRow;
e.Status = UpdateStatus.SkipAllRemainingRows;
}
}
The Bleow Codes I used in Data_Save Areas...
SQLCon.Open();
blah...blah...blah...blah...
SqlTransaction Trans1 = MyItmDatas.WMSCon.BeginTransaction();
MyDataAdapter1.UpdateCommand.Transaction = Trans1;
MyDataAdapter1.InsertCommand.Transaction = Trans1;
MyDataAdapter1.RowUpdating += new SqlRowUpdatingEventHandler(OnRowUpdating);
MyDataAdapter1.RowUpdating += new SqlRowUpdatingEventHandler(OnRowUpdating);
myDataGrid1.CurrentCell = myDataGrid1.FirstDisplayedCell;
myDataGrid1.EndEdit();
try
{
MyDataAdapter1.Update(ItemTable);
Trans1.Commit();
MessageBox.Show(" ITEMS UPDATED TO ....... ITEM MASTER ", " ITEM MASTER UPDATE ");
}
catch (Exception ex)
{
if (Trans1 != null)
{
Trans1.Rollback();
}
MessageBox.Show(ex.Message, "Item Master Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
SQLCon.Close();
MyDataAdapter1.RowUpdating -= new SqlRowUpdatingEventHandler(OnRowUpdating);
myDataGrid1.Refresh();
Related
I have created a form to insert data. When data inserted it shows into datagridview1. I use dataGridView1_MouseClick event to retrieve data into the form. I successfully retrieved textbox data only into my form. I want to retrieve checkbox value which is checked or not. How can i retrieve checkbox value by clicking dataGridView1_MouseClick event.
I use following code for that:
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
try
{
txtID.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
Name.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
}
catch (ApplicationException ex)
{
MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
My result is here
But I want like this:
U can retrive values of other fields in similar like u did
This is for WPF control Checkbox link
I assume checkbox name of movie is movie_chbox
movie_chbox.IsChecked =
dataGridView1.SelectedRows[0].Cells[3].Value.toString() == "1" ?true:false
Similarly you can do same for other too.
This is for winforms control Checkbox link
movie_chbox.Checked =
dataGridView1.SelectedRows[0].Cells[3].Value.toString() == "1" ?true:false
Instead of displaying 0 or 1 in datagridview display "Interested"/"Not Interested" and when you insert/update to database that time insert/update as 0 or 1 for better database mentainance.
Use the checked property of the check box control in your code and change the code for different categories. In your case the final code will be be something like below:
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
try
{
txtID.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
txtName.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
string isCheckedMovie = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
string isCheckedSports = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
string isCheckedReading = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
string isCheckedWriting = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
if (isCheckedMovie == "1")
movieBox.Checked = true;
else
movieBox.Checked = false;
if (isCheckedSports == "1")
sportsBox.Checked = true;
else
sportsBox.Checked = false;
if (isCheckedReading == "1")
readingBox.Checked = true;
else
readingBox.Checked = false;
if (isCheckedWriting == "1")
writingBox.Checked = true;
else
writingBox.Checked = false;
}
catch (ApplicationException ex)
{
MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
Grid check box get checked when in search Box key is pressed .
Grid should not affect on key press of ShowSearchPanelMode of WPF !
XAML Code
<dxg:TableView Name="view" ShowTotalSummary="False" AlternateRowBackground="#FFE5EEF7" AlternationCount="2"
ShowSearchPanelMode="Always"
ShowSearchPanelFindButton="True"
SearchPanelFindMode="FindClick"
ShowSearchPanelCloseButton="True"
ShowGroupPanel="False" AllowColumnMoving="False"
AutoWidth="True" BestFitArea="All" DetailHeaderContent="True" ShowIndicator="False"
BestFitMode="AllRows" AllowEditing="True" >
c# Code
private void dgv_Details_KeyDown(object sender, KeyEventArgs e)
{
try
{
int RowInd = Convert.ToInt32(dgv_Details.GetRowVisibleIndexByHandle(view.FocusedRowData.RowHandle.Value).ToString());
{
if (e.Key == Key.Enter)
{
if (ShowSearchPanelMode.Always.ToString() != "")
{
int RowIndex = Convert.ToInt32(dgv_Details.GetRowVisibleIndexByHandle(view.FocusedRowData.RowHandle.Value).ToString());
string itmId = dgv_Details.GetCellValue(RowIndex, "Item Code").ToString();
string check_ = "false";
itmId = dgv_Details.GetCellValue(RowIndex, "Item Code").ToString();
check_ = dgv_Details.GetCellValue(RowIndex, "IsSelect").ToString();
if (check_ == "false" || check_ == "False")
{
check_ = "true";
}
else
{
check_ = "false";
}
IEnumerable<DataRow> rows = dt.Rows.Cast<DataRow>().Where(r => r["itmId"].ToString() == itmId);
rows.ToList().ForEach(r => r.SetField("IsSelect", check_));
dt.AcceptChanges();
dgv_Details.ItemsSource = null;
dgv_Details.ItemsSource = dt;
dgv_Details.RefreshData();
}
dgv_Details.SetFocusedRowCellValue(ShowSearchPanelMode.Default.ToString(), RowInd);
}
}
}
catch (Exception exc)
{
DXMessageBox.Show(exc.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
I don't properly understand what you're trying to do but in your comment you said
when the focus is on the row I want to check/uncheck checkbox with only Enter key press
The easiest solution i can give you regarding this issue is :
private void dgvw_KeyDown()
if (e.Key == Key.Return)
{
dgvw.NotifyCurrentCellDirty(true);
dgvw.NotifyCurrentCellDirty(false);
}}
///Add this if required
dgvw.CommitEdit(DataGridViewDataErrorContexts.Commit);
Hope this helps :)
datagridview How to skip blank rows deleted?
this is the following error :
Deleted row information cannot be accessed through the row
this is my code: http://pasted.co/bcb3fb31
You have to implement SQL DataTable event handler like the one shown below:
YourDataTable.RowDeleted += new DataRowChangeEventHandler(dataTable_RowChanged);
private void dataTable_RowChanged(object sender, DataRowChangeEventArgs e)
{
DataRow _dr = e.Row as DataRow;
try
{
if (e.Row.RowState == DataRowState.Deleted)
{
// YOUR CODE
}
if (e.Row.RowState == DataRowState.Added) { //OPTIONAL }
if (e.Row.RowState == DataRowState.Modified) { //OPTIONAL}
}
catch (Exception ex) { }
finally { _dr = null; }
}
Hope this may help. Best regards,
I have a DataGridView in winform with 2 combo box columns: 1) Companies, 2) Accounts.
I want to update the accounts combo box according to the selected company.
I have this code:
void recipientsDataGrid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
try
{
ComboBox cb = e.Control as ComboBox;
if (cb != null)
{
cb.SelectedValueChanged -= new EventHandler(companyCombobox_SelectedValueChanged);
cb.SelectedValueChanged += new EventHandler(companyCombobox_SelectedValueChanged);
}
}
catch (Exception ex)
{
}
}
private void companyCombobox_SelectedValueChanged(object sender, EventArgs e)
{
try
{
var currentCell = recipientsDataGrid.CurrentCellAddress;
if (currentCell.X == 3)
{
var sendingCB = sender as DataGridViewComboBoxEditingControl;
int companyId = sendingCB.SelectedValue.ToInt();
DataTable dtAccounts = m_CustomersFunctions.GetCompanyAccounts(companyId);
DataGridViewComboBoxCell cboAccounts = (DataGridViewComboBoxCell)recipientsDataGrid.Rows[currentCell.Y].Cells["Account"];
cboAccounts.ValueMember = "account_id";
cboAccounts.DisplayMember = "AccountName";
cboAccounts.DataSource = dtAccounts;
int defaultAccountId = (from row in dtAccounts.AsEnumerable()
where row.Field<string>("AccountName").EndsWith("*")
select row.Field<int>("account_id")).FirstOrDefault();
if (defaultAccountId > 0)
cboAccounts.Value = defaultAccountId;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
It works fine in the first time I select a company, but when I change the company and try to update the data source for the accounts combo box I'm getting an error:
I tried to add the items manualy and not with a DataSource, and I got the same error.
How can I fix it ?
please...
Try to clear the value of accounts cell before rebind it, like this:
private void companyCombobox_SelectedValueChanged(object sender, EventArgs e)
{
try
{
var currentCell = recipientsDataGrid.CurrentCellAddress;
if (currentCell.X == 3)
{
var sendingCB = sender as DataGridViewComboBoxEditingControl;
int companyId = sendingCB.SelectedValue.ToInt();
DataTable dtAccounts = m_CustomersFunctions.GetCompanyAccounts(companyId);
DataGridViewComboBoxCell cboAccounts = (DataGridViewComboBoxCell)recipientsDataGrid.Rows[currentCell.Y].Cells["Account"];
cboAccounts.Value = null; //Add this code
cboAccounts.ValueMember = "account_id";
cboAccounts.DisplayMember = "AccountName";
cboAccounts.DataSource = dtAccounts;
int defaultAccountId = (from row in dtAccounts.AsEnumerable()
where row.Field<string>("AccountName").EndsWith("*")
select row.Field<int>("account_id")).FirstOrDefault();
if (defaultAccountId > 0)
cboAccounts.Value = defaultAccountId;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I had the same problem in vb.net .
Not sure if my solution is good, but it works for me.
Briefly: I create a new temporary "DataGridViewComboBoxCell" object, I assign the "DataSource" and the "Value" (which must belong to "DataSource" !!! otherwise the error "value is not valid" comes out) and assign the new object to correct cell in my "DataGridView" main object, like this:
Dim oDataGridViewComboBox As New DataGridViewComboBox With {
.DataSource = MyDataSource
.Value = MyCorrectValueContainedInDataSource
}
oMyDataGridView.Rows(iLineOfComboBox).Cells("ComboBoxColumnName") = oDataGridViewComboBox
The error "value is not valid" is thrown because the ComboBox value is not included among those present in "DataSource".
P.S.: Sorry, I don't know C# ... but the problem is the same, and I have found this post during a search of solution.
i have this project am working on the registration form has four dropdownlist .two are been populated at page load event from the database
if (!IsPostBack)
{
if (!getState()) { return; }
if (!GetFaculty()) { return; }
}
the rest two are been populated at the selectIndexchange of the two (state and faculty)
protected void ddlFaculty_OnSelectedIndexChanged(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
try
{
string sqltext = #"Select Name from Department where FacultyID=" + this.ddlFaculty.SelectedValue.ToString();
List<Department> mlist = new List<Department>();
mlist = ServiceProvider.Instance().GetDepartmentService().GetDepartment_GetDepartment(sqltext);
if (mlist.IsNullOrEmpty()) { return; }
this.ddlDepartment.DataSource = mlist;
this.ddlDepartment.DataTextField = "Name";
this.ddlDepartment.DataValueField = "DepartmentID";
this.ddlDepartment.DataBind();
this.ddlDepartment.Items.Insert(0, new ListItem("--Select Department--", "0"));
}
catch (Exception ex) { return; }
}
}
protected void ddstate_OnSelectedIndexChanged(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
try
{
string sqltext = #"Select Name from University where StateID=" + this.ddlState.SelectedValue.ToString();
List<University> mlist = new List<University>();
mlist = ServiceProvider.Instance().GetUniversityService().GetUniversity_UniversityName(sqltext);
this.dDUniversity.DataSource = mlist;
this.dDUniversity.DataTextField = "Name";
this.dDUniversity.DataValueField = "UniversityID";
this.dDUniversity.DataBind();
this.dDUniversity.Items.Insert(0, new ListItem("-- Select University--", "0"));
this.dDUniversity.SelectedIndex = 0;
}
catch (Exception ex) { return; };
}
}
the problem now is that once i select a value from the selectedIndexChanged of the ddstate in ddUniversity it works fine , then selecting value from the selectedIndexChanged of the ddfaculty from the ddDepartment will automatically reset the ddUniversity and also clicking the signup button equally rests every thing in the ddUniversity and ddDepartment.
this my html code
Experiment with UpdatePanels or use plain AJAX instead to load the DropDowns