I just want to ask how to stop the selected value changed event in my code. I have both SelectedValueChanged event and SelectedIndexChanged event. I am using SelectedIndexChanged event because to find any duplication on my gridview for you to understand, here is my code.
SelectedValueChanged code:
private void cmbField_SelectedValueChanged(object sender, EventArgs e)
{
DataGridViewRow GridRowLoc = this.dgvFilter.CurrentRow;
AddGrid(iRowIdx);
int iRowCount = this.dgvFilter.RowCount - 1;
if (this.cmbField.Text != "System.Data.DataRowView")
{
this.dgvFilter.Rows[iRowIdx].Cells["ColumnFieldName"].Value = this.cmbField.Text;
this.dgvFilter.Rows[iRowIdx].Cells["FieldName"].Value = this.cmbField.SelectedValue;
if (iRowCount <= iRowIdx)
{
DataRow drow = dttable.NewRow();
drow["ColumnNames"] = this.cmbField.Text;
drow["FieldName"] = this.cmbField.SelectedValue;
drow["Alias"] = string.Empty;
drow["DataType"] = string.Empty;
drow["Outputs"] = false;
drow["SortType"] = string.Empty;
drow["SortOrder"] = string.Empty;
drow["GroupBy"] = string.Empty;
drow["Filter"] = string.Empty;
drow["Or1"] = string.Empty;
drow["Or2"] = string.Empty;
drow["Or3"] = string.Empty;
drow["Or4"] = string.Empty;
drow["Or5"] = string.Empty;
drow["Or6"] = string.Empty;
drow["Or7"] = string.Empty;
drow["Or8"] = string.Empty;
drow["Or9"] = string.Empty;
drow["Or10"] = string.Empty;
dttable.Rows.Add(drow);
}
else
{
int irow = 0;
foreach (DataRow dr in dttable.Rows)
{
if (irow == iRowIdx)
{
dr["ColumnNames"] = this.cmbField.Text;
dr["FieldName"] = this.cmbField.SelectedValue;
}
irow++;
}
}
CheckAlias(iRowIdx, this.cmbField.Text, dgvFilter);
checkcellvalue(this.cmbField.Text, iRowIdx);
CheckSorting();
if (bGroupBySelected == true)
{
this.dgvFilter.Rows[iRowIdx].Cells["GroupBy"].Value = "Group By";
}
this.dgvFilter.DataSource = dttable;
dsFilter.AcceptChanges();
this.cmbField.Visible = false;
}
//checkcellvalue(this.cmbField.Text, iRowIdx);
//MessageBox.Show(arr_Filter[0]);
CheckoutputEnable();
}
Then here is my SelectedIndexChanged code:
private void cmbField_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (dgvFilter.Rows.Count > 1)
{
int count = this.dgvFilter.Rows.Count;
DataRowView oDataRowView = cmbField.SelectedItem as DataRowView;
string sValue = string.Empty;
if (oDataRowView != null)
{
sValue = oDataRowView.Row["FieldDescription"] as string;
}
for (int j = 0; j < count; j++)
{
sValue = this.cmbField.Text;
if ((j + 2) != dgvFilter.Rows.Count)
{
if ((sValue == this.dgvFilter.Rows[j].Cells["ColumnFieldName"].Value.ToString()))
{
if (this.dgvFilter.Rows.Count > 2)
{
MessageBox.Show("Field already in the list");
DataGridViewRow GridRowLoc2 = this.dgvFilter.CurrentRow;
this.dgvFilter.Rows.Remove(GridRowLoc2);
break;
}
}
}
}
}
}
catch (Exception ex)
{
}
}
My code upon loading the form is this in case you guys need.
private void FormAdhocReportViewer_Load(object sender, EventArgs e)
{
try
{
//string sample = "";
sXMLResult = SQLScript;
AddGrid(0);
adhoc.RowID = CurrentUserNameRowID;
adhoc.FieldGroup = toolStripReportGroup.Text;
XMLDOC = adhoc.get_sp_Get_Field_Settings();
if (RowID == "0")
{
// XMLDOC = adhoc.get_sp_Get_Field_Settings();
LoadDataSet(XMLFILTER);
}
else
{
// XMLDOC = sXMLFieldSettings;
XMLFieldQuery = XMLFieldQuery.Replace("#", "<").Replace("+", ">").Replace("*", "/");
LoadDataSet(XMLFieldQuery);
}
LoadComboField();
}
catch { }
}
LoadComboField is for the items in the combobox, the code is this
private void LoadComboField()
{
ReadXMLData(XMLDOC, dsCombo);
dt = dsCombo.Tables[0];
DataView dv1 = new DataView(dsCombo.Tables[0]);
this.cmbField.Items.Clear();
this.cmbField.DataSource = dv1;
this.cmbField.DisplayMember = "FieldDescription";
this.cmbField.ValueMember = "FieldName";
}
Everytime the code
DataGridViewRow GridRowLoc2 = this.dgvFilter.CurrentRow;
this.dgvFilter.Rows.Remove(GridRowLoc2);
executes the event SelectedValueChanged executes to.. I just want to stop the SelectedValueChangedEvent it's so hard to explain because my code is too complicated.
What about simply removing the event handler?
Just do:
if (<whatever>)
{
this.cmbField.SelectedValueChanged -= cmbField_SelectedValueChanged;
}
Related
I am needing that if there is no CheckBox selected in the DataGridView the button Uno and the button Varios are disabled.
If a single CheckBox is selected, the button Uno is enabled and the button Varios disabled.
And if there is more than one CheckBox selected, the button Uno is disabled and the button Varios is enabled.
But, the following happens:
The code I use is the following:
public Form1()
{
InitializeComponent();
btnUno.Enabled = false;
btnVarios.Enabled = false;
}
To enable and disable the buttons:
private void dtgTitulo_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
int contador = 0;
foreach (DataGridViewRow row in dtgTitulo.Rows)
{
if (row.Cells["Seleccione"].Value != null && row.Cells["Seleccione"].Value.Equals(true))//Columna de checks
{
contador++;
if (contador <= 0)
{
btnUno.Enabled = false;
btnVarios.Enabled = false;
}
else if (contador == 1)
{
btnUno.Enabled = true;
btnVarios.Enabled = false;
}
else
{
btnUno.Enabled = false;
btnVarios.Enabled = true;
}
}
}
}
Can someone help me? Any suggestion?
UPDATE
HOW TO I LOAD THE DATAGRIDVIEW WITH CHECKBOXES:
private DataTable Query()
{
DataTable datos = new DataTable();
SqlConnection sqlConn = new SqlConnection("STRING");
try
{
sqlConn.Open();
string consulta = "SELECT Titulo AS TÃtulo FROM V_CuetaWeb GROUP BY titulo ORDER BY titulo DESC";
SqlCommand sqlCommand = new SqlCommand(consulta, sqlConn);
SqlDataAdapter da = new SqlDataAdapter(sqlCommand);//este se encarga de inicializar el command
da.Fill(datos);
sqlConn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return datos;
}
I form_Load:
private void Form1_Load(object sender, EventArgs e)
{
ds = new DataSet();
ds.Tables.Add(Query());
ds.Tables[0].Columns.Add("Seleccione", typeof(bool));
dtgTitulo.DataSource = ds.Tables[0];
}
Try Below code:
AS per #JIMI's suggestion
private void dtgTitulo_CellMouseUp(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex != 1) return;
dtgTitulo.CommitEdit(DataGridViewDataErrorContexts.Commit);
var contador = dtgTitulo.Rows.OfType<DataGridViewRow>().Count(r => (r.Cells[1].Value != null) && ((bool)r.Cells[1].Value == true));
if (contador <= 0)
{
btnUno.Enabled = false;
btnVarios.Enabled = false;
}
else
{
if (contador == 1)
{
btnUno.Enabled = true;
btnVarios.Enabled = false;
}
else
{
btnUno.Enabled = false;
btnVarios.Enabled = true;
}
}
}
after click on checkboxes they show/hide ticks, but value in cell doesn't change immediately. call EndEdit to apply them.
private void dtgTitulo_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex < 0 || dtgTitulo.Columns[e.ColumnIndex].Name != "Seleccione")
return;
dtgTitulo.EndEdit();
int contador = 0;
foreach (DataGridViewRow row in dtgTitulo.Rows)
{
if (Equals(true, row.Cells["Seleccione"].Value))
{
contador++;
if (contador > 1)
break;
}
}
btnUno.Enabled = contador == 1;
btnVarios.Enabled = contador > 1;
}
p.s. note optimizations made to avoid unnecessary iterations
The program i have create for "Inventory system". And also i have create GridControl from Devexpress Tools. how do i convert this code to Devexpress gridcontrol..
please refer attached image GridControl
private void dgvinvoicesummary_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
int id = e.RowIndex;
DataGridViewRow row = dgvinvoicesummary.Rows[id];
int ddl1 = Convert.ToInt32(row.Cells[2].Value.ToString());
if (dgvinvoicesummary.Columns[e.ColumnIndex].Name == "Update")
{
invoiceSummary Obj = new invoiceSummary
{
CustomerName = row.Cells["customerName"].Value.ToString(),
InvoiceID = Convert.ToInt32(row.Cells["invoiceId"].Value.ToString()),
IssueDate = row.Cells["issue_date"].Value.ToString(),
DueDate = row.Cells["due_date"].Value.ToString(),
Status = row.Cells["Status"].Value.ToString()
};
frmAddinvoice fm = new frmAddinvoice(Obj);
fm.ShowDialog();
this.Close();
GetInvoiceSummaryData();
}
if (dgvinvoicesummary.Columns[e.ColumnIndex].Name == "delete")
{
DeleteInvoiceSummaryRow(ddl1);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The Answer should be like this
private void gridView1_RowCellClick(object sender, RowCellClickEventArgs e)
{
int id = e.RowHandle;
DataRow row = gridView1.GetDataRow(id);
int ddl1 = Convert.ToInt32(gridView1.GetRowCellValue(id, "invoiceId").ToString());
if (e.Column.Name=="ActionUpdate")
{
invoiceSummary Obj = new invoiceSummary
{
CustomerName = gridView1.GetRowCellValue(id, "customerName").ToString(),
InvoiceID = Convert.ToInt32(gridView1.GetRowCellValue(id,"invoiceId").ToString()),
IssueDate = gridView1.GetRowCellValue(id,"issue_date").ToString(),
DueDate = gridView1.GetRowCellValue(id,"due_date").ToString(),
Status = gridView1.GetRowCellValue(id,"Status").ToString(),
PrivateNote = gridView1.GetRowCellValue(id,"privateNotes").ToString(),
PadiAmount = Convert.ToDouble(gridView1.GetRowCellValue(id,"Amount_Paid").ToString()),
Balance = Convert.ToDouble(gridView1.GetRowCellValue(id,"Balance").ToString()),
PaymentType = gridView1.GetRowCellValue(id,"paymentType").ToString(),
DateOfPayment = gridView1.GetRowCellValue(id,"DateOfPayment").ToString(),
TotalDiscount = Convert.ToDouble(gridView1.GetRowCellValue(id,"TotalDiscount").ToString()),
PackagingAmount = Convert.ToDouble(gridView1.GetRowCellValue(id,"PackagingAmount").ToString()),
CustomerNote = gridView1.GetRowCellValue(id,"CustomerNote").ToString(),
TaxTotalAmount = Convert.ToDouble(gridView1.GetRowCellValue(id,"Tax_Amount").ToString()),
Valuedata = Convert.ToDouble(gridView1.GetRowCellValue(id,"Amount").ToString()),
TotalSubAmount = Convert.ToDouble(gridView1.GetRowCellValue(id,"Total_Amount").ToString()),
};
frmAddinvoice fm = new frmAddinvoice(Obj);
fm.ShowDialog();
this.Close();
GetInvoiceSummaryData();
}
else
{
MessageBox.Show("");
}
}
My question is exactly the same as this Pls. don't down vote as the thread did not have answers.
Problem in Brief:
I have an CustomGridView, a type of DataGridView. The below code is attached to it. When I drop the datagridview in design time I can see the columns are all in proper but except for the name of the datagridviewcolumn names are different and is not what I gave.
In runtime the Columns are duplicated. Could not figure out why.
Property Page looks like this
Code:
public class CustomAccountDataGridView : DataGridView
{
private bool _paddingOn = true;
public bool PaddingOn
{
get { return _paddingOn; }
set { _paddingOn = value; }
}
public CustomAccountDataGridView()
{
this.AutoGenerateColumns = false;
this.Columns.Clear();
DataGridViewTextBoxColumn columnAccountID = new DataGridViewTextBoxColumn();
columnAccountID.DataPropertyName = "ACCOUNTID";
columnAccountID.Name = "colACCOUNTID";
columnAccountID.HeaderText = "A/c";
columnAccountID.Width = 110;
columnAccountID.Visible = false;
this.Columns.Add(columnAccountID);
DataGridViewTextBoxColumn columnClientAccountID = new DataGridViewTextBoxColumn();
columnClientAccountID.DataPropertyName = "CLIENTACCOUNTID";
columnClientAccountID.Name = "colCLIENTACCOUNTID";
columnClientAccountID.HeaderText = "Client A/c";
columnClientAccountID.Width = 110;
this.Columns.Add(columnClientAccountID);
DataGridViewTextBoxColumn columnParticipantID = new DataGridViewTextBoxColumn();
columnParticipantID.DataPropertyName = "PARTICIPANTID";
columnParticipantID.Name = "colPARTICIPANTID";
columnParticipantID.HeaderText = "Participant";
columnParticipantID.Width = 60;
this.Columns.Add(columnParticipantID);
DataGridViewTextBoxColumn columnAccountName = new DataGridViewTextBoxColumn();
columnAccountName.Name = "colACCOUNTNAME";
columnAccountName.HeaderText = "A/c Name";
columnAccountName.Width = 200;
columnAccountName.ReadOnly = true;
this.Columns.Add(columnAccountName);
DataGridViewTextBoxColumn columnXsactValue = new DataGridViewTextBoxColumn();
columnXsactValue.DataPropertyName = "XSACTVALUE";
columnXsactValue.Name = "colXSACTVALUE";
columnXsactValue.Width = 110;
columnXsactValue.HeaderText = "Value";
columnXsactValue.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
columnXsactValue.DefaultCellStyle.Format = "N2";
this.Columns.Add(columnXsactValue);
}
protected override void OnDataBindingComplete(DataGridViewBindingCompleteEventArgs e)
{
string sClientID = string.Empty;
foreach (DataGridViewRow dvr in (this.Rows))
{
for (int i = 0; i < dvr.Cells.Count; i++)
{
if (this.Columns[i].DataPropertyName == "ACCOUNTID")
{
if (dvr.Cells["colACCOUNTID"].Value != null)
{
sClientID = dvr.Cells["colACCOUNTID"].Value.ToString();
dvr.Cells["colACCOUNTNAME"].Value = sClientID; //utility.ClientExtention.getAccountName(sClientID);
break;
}
}
}
}
base.OnDataBindingComplete(e);
}
protected override void OnEditingControlShowing(DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control.GetType() == typeof(DataGridViewTextBoxEditingControl))
{
(e.Control as TextBox).CharacterCasing = CharacterCasing.Upper;
}
base.OnEditingControlShowing(e);
}
protected override void OnCellValueChanged(DataGridViewCellEventArgs e)
{
string sClientAccountID = string.Empty;
string sParticipantID = "JKB";
if (e.RowIndex >= 0)
{
if (this.Columns[e.ColumnIndex].DataPropertyName == "CLIENTACCOUNTID")
{
if (this[e.ColumnIndex, e.RowIndex].Value != null)
{
if (this[e.ColumnIndex, e.RowIndex].Value.ToString().Length != 0)
{
if (this.PaddingOn)
{
sClientAccountID = this[e.ColumnIndex, e.RowIndex].Value.ToString().ToUpper().PadLeft(13, '0');
}
else
{
sClientAccountID = this[e.ColumnIndex, e.RowIndex].Value.ToString().ToUpper();
}
this[e.ColumnIndex, e.RowIndex].Value = sClientAccountID;
}
}
}
if (this.Columns[e.ColumnIndex].DataPropertyName == "PARTICIPANTID")
{
if (this[e.ColumnIndex, e.RowIndex].Value != null)
{
if (this[e.ColumnIndex, e.RowIndex].Value.ToString().Length != 0)
{
sParticipantID = this[e.ColumnIndex, e.RowIndex].Value.ToString().ToUpper();
}
this[e.ColumnIndex, e.RowIndex].Value = sParticipantID;
}
}
if (sClientAccountID != string.Empty & sParticipantID != string.Empty)
{
this["ACCOUNTNAME", e.RowIndex].Value = (string.Format("{0}-{1}", sParticipantID, sClientAccountID));
}
}
base.OnCellValueChanged(e);
}
}
}
I found something that seems to work here:
protected override void InitLayout()
{
base.InitLayout();
SetColumns();
}
SetColumns is the subroutine to add the columns I want.
In case it can be helpful, I have just encountered this problem, on VS 2015 Express, with a standard DataGridView. The problem appeared as soon as I renamed my custom columns. Reverting to default names fixed the problem, as much as flushing the custom columns and keeping the duplicates. I can reproduce and fix the problem anytime, it seems consistent. Note that when both original and duplicate columns are in, there is no trace of the duplicates in the designer code(Designer.cs), don't ask me why...
I am selecting a row from Gridview, working good except for checkbox, like I am assigning value of checkbox retreived from gridview to checkbox that is placed on web form but it isn't represented by checkbox on form, it shows empty checkbox in every case
if (gridviewDesignations.SelectedRow.Cells[5].Text == " ")
{
chkIsHead.Text = gridviewDesignations.SelectedRow.Cells[5].Text;
}
in short, checkbox is not picking value from gridview
Update:
tried this too:
CheckBox chkIsHead = (CheckBox) gridviewDesignations.SelectedRow.Cells[5].Controls[0];
if (chkIsHead.Checked == false)
{
chkIsHead.Checked = false;
}
else
{
chkIsHead.Checked = true;
}
Update:
my full code:
public partial class frmDesignations : System.Web.UI.Page
{
AccessibleVariables accessVariables = new AccessibleVariables(); //Used to access global variables
public void Clear(params TextBox[] txtBoxes)
{
foreach (TextBox txtbx in txtBoxes)
{
txtbx.Text = "";
}
}
public void fillddlDepartments()
{
ManageDepartmentsBizz mngDepBizz = new ManageDepartmentsBizz();
DataSet ds = (DataSet)mngDepBizz.SelectDepartments();
if (ds.Tables[0].Rows.Count != 0)
{
ddlDepartments.DataValueField = "DepID";
ddlDepartments.DataTextField = "DepName";
ddlDepartments.DataSource = ds.Tables[0];
// ddlDepartments.SelectedIndex = -1;
ddlDepartments.DataBind();
ddlDepartments.Items.Insert(0, "--Select--");
}
//else
// ddlDepartments.SelectedIndex = -1;
}
protected void Page_Load(object sender, EventArgs e)
{
if (Session.Count <= 0)
{
Response.Redirect("login.aspx");
}
lblMsgPopUp.Visible = false;
if (!IsPostBack)
{
fillddlDepartments();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
int DepartmentID = Convert.ToInt32(ddlDepartments.SelectedValue);
bool IsHead = Convert.ToBoolean(chkIsHead.Checked);
DesignationsBizz DesigBizz = new DesignationsBizz(-1, txtTitle.Text, DepartmentID, txtContactNo.Text, IsHead);
//-1 is bogus,used to fill parameters criteria i.e no of params
ManageDesignationsBizz mngDesigBizz = new ManageDesignationsBizz();
bool Result = mngDesigBizz.Insert(DesigBizz);
if (Result == true)
{
HiddenFieldSetMessage.Value = "Saved";
HiddenFieldShowMessage.Value = "True";
Clear(txtTitle, txtSelectedID, txtContactNo);
}
else
{
HiddenFieldSetMessage.Value = "RecordAlreadyExists";
HiddenFieldShowMessage.Value = "True";
}
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotSaved";
HiddenFieldShowMessage.Value = "True";
}
}
protected void btnSearchPopup_Click(object sender, EventArgs e)
{
string DesignationTitle = txtDesignationPopUp.Text;
ManageDesignationsBizz mngDepsBizz = new ManageDesignationsBizz();
DataSet ds = (DataSet)mngDepsBizz.Select(DesignationTitle);
if (ds.Tables[0].Rows.Count != 0)
{
lblMsgPopUp.Visible = false;
gridviewDesignations.DataSource = ds.Tables[0];
gridviewDesignations.DataBind();
gridviewDesignations.Visible = true;
}
else
{
lblMsgPopUp.Visible = true;
gridviewDesignations.Visible = false;
}
}
protected void gridviewDesignations_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
string DesignationTitle = txtDesignationPopUp.Text;
ManageDesignationsBizz mngDepBizz = new ManageDesignationsBizz();
DataSet ds = (DataSet)mngDepBizz.Select(DesignationTitle);
if (ds.Tables[0].Rows.Count != 0)
{
gridviewDesignations.PageIndex = e.NewPageIndex;
gridviewDesignations.DataSource = ds.Tables[0];
gridviewDesignations.DataBind();
gridviewDesignations.Visible = true;
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
if (gridviewDesignations.SelectedRow != null)
{
if (gridviewDesignations.SelectedRow.Cells[1].Text == " ")
{
txtSelectedID.Text = string.Empty;
}
else
{
txtSelectedID.Text = gridviewDesignations.SelectedRow.Cells[1].Text;
}
if (gridviewDesignations.SelectedRow.Cells[2].Text == " ")
{
txtTitle.Text = string.Empty;
}
else
{
txtTitle.Text = gridviewDesignations.SelectedRow.Cells[2].Text;
}
if (gridviewDesignations.SelectedRow.Cells[3].Text == " ")
{
ddlDepartments.SelectedValue = string.Empty;
}
else
{
ddlDepartments.SelectedValue = gridviewDesignations.SelectedRow.Cells[3].Text;
accessVariables.DepID = Convert.ToInt32(gridviewDesignations.SelectedRow.Cells[3].Text);
ViewState["depID"] = accessVariables.DepID;
}
if (gridviewDesignations.SelectedRow.Cells[4].Text == " ")
{
txtContactNo.Text = string.Empty;
}
else
{
txtContactNo.Text = gridviewDesignations.SelectedRow.Cells[4].Text;
}
CheckBox chkIsHead = (CheckBox) gridviewDesignations.SelectedRow.Cells[5].Controls[0];
if (chkIsHead.Checked == false)
{
chkIsHead.Checked = false;
}
else
{
chkIsHead.Checked = true;
}
gridviewDesignations.DataBind();
gridviewDesignations.SelectedIndex = -1;
HiddenFieldShowHideButtons.Value = "True";
}
}
protected void btnUpdatePopUp_Click(object sender, EventArgs e)
{
try
{
int id = Convert.ToInt32(txtSelectedID.Text);
int DepartmentID = Convert.ToInt32(ddlDepartments.SelectedValue);
bool IsHead = Convert.ToBoolean(chkIsHead.Checked);
DesignationsBizz DesigBizz = new DesignationsBizz(id, txtTitle.Text, DepartmentID, txtContactNo.Text, IsHead );
ManageDesignationsBizz mngDesigBizz = new ManageDesignationsBizz();
bool Result = mngDesigBizz.Update(DesigBizz);
if (Result == true)
{
HiddenFieldSetMessage.Value = "Updated";
HiddenFieldShowMessage.Value = "True";
Clear(txtSelectedID, txtTitle, txtContactNo);
}
else
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
protected void btnDeletePopUp_Click(object sender, EventArgs e)
{
try
{
int ID = Convert.ToInt32(txtSelectedID.Text.Trim());
ManageDesignationsBizz mngDepBizz = new ManageDesignationsBizz();
mngDepBizz.Delete(ID);
Clear(txtTitle, txtSelectedID, txtContactNo);
HiddenFieldSetMessage.Value = "Deleted";
HiddenFieldShowMessage.Value = "True";
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotDeleted";
HiddenFieldShowMessage.Value = "True";
}
}
protected void btnClosePopup_Click(object sender, EventArgs e)
{
Clear(txtTitle, txtSelectedID, txtContactNo);
}
protected void ddlDepartments_SelectedIndexChanged(object sender, EventArgs e)
{
if (txtSelectedID.Text != "")
{
accessVariables.DepID = Convert.ToInt32(ddlDepartments.SelectedValue);
ViewState["depID"] = accessVariables.DepID;
}
else
{
accessVariables.DepID = Convert.ToInt32(ddlDepartments.SelectedValue);
ViewState["depID"] = accessVariables.DepID;
}
}
protected void chkIsHead_CheckedChanged(object sender, EventArgs e)
{
if (txtSelectedID.Text != "")
{
int DepID = Convert.ToInt32(ViewState["depID"]);
ManageDesignationsBizz mngDesig = new ManageDesignationsBizz();
bool isHead = mngDesig.SelectIsHeadExistsByDepID(DepID);
if (isHead == true)
{
HiddenFieldSetMessage.Value = "HeadExists";
HiddenFieldShowMessage.Value = "True";
chkIsHead.Checked = false;
}
}
else
{
int DepID = Convert.ToInt32(ViewState["depID"]);
ManageDesignationsBizz mngDesig = new ManageDesignationsBizz();
bool isHead = mngDesig.SelectIsHeadExistsByDepID(DepID);
if (isHead == true)
{
HiddenFieldSetMessage.Value = "HeadExists";
HiddenFieldShowMessage.Value = "True";
chkIsHead.Checked = false;
}
}
}
}
I believe the following is what you need to do:
Then select EditProgrammatically.
I'm not sure if yoou'll need to manually put data into the grid though but that won't be too hard. Examples can be seen here : http://msdn.microsoft.com/en-us/library/system.data.datatable(v=vs.110).aspx
PS : You can set the DataSource in the grid view to the DataTable.
I have the following program that will send (output) information to a text file, but now I want to read (input) from the text file. Any suggestions would be greatly appreciated. I have commented out a couple of things that "I think" I need to do; but I am not really certain how to proceed.
using System.Windows.Forms;
using System.IO;
namespace Input_Output
{
public partial class Grades : Form
{
private StreamWriter output;
private StreamReader input;
public Grades()
{
InitializeComponent();
}
private void label4_Click(object sender, EventArgs e)
{
}
private void btnCreate_Click(object sender, EventArgs e)
{
btnEnter.Visible = true;
btnClose.Visible = true;
txtFirst.Visible = true;
txtLast.Visible = true;
lblFirst.Visible = true;
lblLast.Visible = true;
listBox1.Visible = true;
lblStatus.Visible = true;
lblGrade.Visible = true;
lblCourse.Visible = true;
cmbID.Visible = true;
lblID.Visible = true;
txtCourse.Visible = true;
txtGrade.Visible = true;
lblStatus.Visible = true;
DialogResult result;
string fileName;
using (SaveFileDialog chooser = new SaveFileDialog())
{
result = chooser.ShowDialog();
fileName = chooser.FileName;
}
output = new StreamWriter(fileName);
btnCreate.Enabled = false;
txtFirst.Visible = true;
txtLast.Visible = true;
lblFirst.Visible = true;
lblLast.Visible = true;
btnEnter.Visible = true;
btnClose.Visible = true;
}
private void btnClose_Click(object sender, EventArgs e)
{
//Close button pushes information from the listbox in to the text file
output.Close();
lblStatus.ForeColor = Color.Red;
lblStatus.Text = "Output File";
btnCreate.Enabled = true;
listBox1.Items.Clear();
cmbID.Text = "";
}
private void btnEnter_Click(object sender, EventArgs e)
{
// Enter button sends information to the list box, a Message Box prompts user to check for accuracy.
//Close button pushes information to the Text file.
string last = "";
string first = "";
string course = "";
string grade = "";
if (txtFirst.Text != "" && txtLast.Text != "" && txtCourse.Text != "")
{
last = txtFirst.Text;
first = txtLast.Text;
course = txtCourse.Text;
grade = txtGrade.Text;
output.WriteLine (last + "\t"+ "\t" + first + ":"+ "\t" + cmbID.SelectedItem + "_" + course + "_" + grade );
listBox1.Items.Add(txtLast.Text + "," + txtFirst.Text + ":" + cmbID.SelectedItem + "-" + txtCourse.Text + "-" + txtGrade.Text);
lblStatus.ForeColor = Color.Navy;
lblStatus.Text = "Entry Saved";
txtFirst.Text = "";
txtLast.Text = "";
txtCourse.Text = "";
txtGrade.Text = "";
txtFirst.Focus();
}
else
{
lblStatus.ForeColor = Color.Red;
lblStatus.Text = "Empty text box or boxes";
}
MessageBox.Show("Please verify that the information is correct before proceeding");
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Grades_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result;
string fileName;
using (OpenFileDialog chooser = new OpenFileDialog())
{
result = chooser.ShowDialog();
fileName = chooser.FileName;
}
//while loop?
//if variable is null, it's the end of the record
//variable= !null
//txt read int variable TxtFile.Text += Rec + "\r\n"; while rec !=null;
}
}
}
To read a text file one line at a time you can do like this:
using System.IO;
using (var reader = new StreamReader(fileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// Do stuff with your line here, it will be called for each
// line of text in your file.
}
}
There are other ways as well. For example, if the file isn't too big and you just want everything read to a single string, you can use File.ReadAllText()
myTextBox.Text = File.ReadAllText(fileName);
It's just one line of code:
string content = System.IO.File.ReadAllText(#"C:\textfile.txt");
Try this:
if(result == DialogResult.OK && fileName != null)
{
try
{
var fileText=File.ReadAllText(fileName);
}
catch(Exception ex)
{
//Handle exception here
}
}
It will read all the data from the selected file into the fileText variable.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace part_B_19
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
StreamReader sr = new StreamReader(#"C:\Users\Acer\Documents\Visual Studio 2012\Projects\combobox.txt");
string line = sr.ReadLine();
while (line != null)
{
comboBox1.Items.Add(line);
line = sr.ReadLine();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Sample program demonstrating FILE i/o in C#
class Items
{
public int itemID { get; set; }
public string itemName { get; set; }
public int itemNo { get; set; }
public string pkgdate { get; set; }
}
class Program
{
private static string connectionString = "...";
static void Main(string[] args)
{
string streadpath = #"I:\itemdata.txt";
string stwritepath = #"I:\itemdata1.txt";
string stcopypath = #"I:\itemdata2.txt";
List<Items> li_all = new List<Items>();
List<Items> li_db = new List<Items>();
List<Items> li_valid = new List<Items>();
List<Items> li_invalid = new List<Items>();
li_all = stread_file(streadpath);
li_invalid = validate(li_all);
li_db = retrievefromDB();
bool x = stwrite_invalid(li_db, stwritepath);
bool y = stcopy_file(streadpath, stcopypath);
}
static List<Items> stread_file(string stpath)
{
List<Items> stli = new List<Items>();
using (StreamReader SR = new StreamReader(stpath))
{
string line = "";
while ((line = SR.ReadLine()) != null)
{
string[] linevalues = line.Split(',');
Items obj = new Items();
obj.itemID = int.Parse(linevalues[0]);
obj.itemName = linevalues[1];
obj.itemNo = int.Parse(linevalues[2]);
obj.pkgdate = linevalues[3];
stli.Add(obj);
}
}
return stli;
}
static List<Items> validate(List<Items> stli)
{
List<Items> li_valid = new List<Items>();
List<Items> li_invalid = new List<Items>();
DateTime parsed;
foreach (Items stit in stli)
{
if(DateTime.TryParseExact(stit.pkgdate, "MM/dd/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out parsed))
{
li_valid.Add(stit);
}
else
{
li_invalid.Add(stit);
}
}
InsertDataToDb(li_valid);
return li_invalid;
}
static bool stwrite_invalid(List<Items> stli,string stpath)
{
using (StreamWriter SW = new StreamWriter(stpath))
{
foreach(Items stit in stli)
{
SW.WriteLine(stit.itemID + "," + stit.itemName + "," + stit.itemNo + "," + stit.pkgdate);
}
}
return true;
}
static bool stcopy_file(string stsourcepath, string stdestinationpath)
{
File.Copy(stsourcepath, stdestinationpath);
return true;
}
static void InsertDataToDb(List<Items> stli)
{
var records = stli;
using (SqlConnection con = new SqlConnection(connectionString))
{
StringBuilder nonQuery = new StringBuilder();
foreach (var item in records)
{
nonQuery.AppendFormat("INSERT INTO dbo.Smartphone VALUES ({0}, '{1}', {2}, '{3}');",
item.itemID,
item.itemName,
item.itemNo,
item.pkgdate);
}
SqlCommand cmd = new SqlCommand(nonQuery.ToString(),con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
static List<Items> retrievefromDB()
{
List<Items> stli = new List<Items>();
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from dbo.Smartphone", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Items obj = new Items();
obj.itemID = (int)dt.Rows[i]["ID"];
obj.itemName = dt.Rows[i]["Name"].ToString();
obj.itemNo = (int)dt.Rows[i]["Num"];
obj.pkgdate = dt.Rows[i]["RDate"].ToString();
stli.Add(obj);
}
}
return stli;
}
}
namespace CDKatalog
{
public partial class KorisnickoUputstvo : System.Web.UI.Page
{
string[] izvodjac = new string[20];
string[] nazivAlbuma = new string[20];
string[] zanr = new string[20];
string[] godinaIzdavanja = new string[20];
string[] izdavackaKuca = new string[20];
string[] slikaOmota = new string[20];
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 1990; i <= 2019; i++)
{
DropDownList2.Items.Add(i.ToString());
}
StreamReader sr = File.OpenText(Server.MapPath(#"\textFajl\katalog.txt"));
string sadrzaj = sr.ReadToEnd();
int brojac = 1;
int j = 0;
for (int i = 0; i < sadrzaj.Length; i++)
{
if (sadrzaj[i] == '^') { j++; brojac++; }
else if (sadrzaj[i] == '|')
{
brojac++;
}
else if (brojac % 6 == 1)
{
izvodjac[j] = izvodjac[j] + sadrzaj[i];
}
else if (brojac % 6 == 2)
{
nazivAlbuma[j] = nazivAlbuma[j] + sadrzaj[i];
}
else if (brojac % 6 == 3)
{
zanr[j] = zanr[j] + sadrzaj[i];
}
else if (brojac % 6 == 4)
{
godinaIzdavanja[j] = godinaIzdavanja[j] + sadrzaj[i];
}
else if (brojac % 6 == 5)
{
izdavackaKuca[j] = izdavackaKuca[j] + sadrzaj[i];
}
else if (brojac % 6 == 0)
{
slikaOmota[j] = slikaOmota[j] + sadrzaj[i];
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Izvodjac", typeof(string));
dt.Columns.Add("Naziv Albuma", typeof(string));
dt.Columns.Add("Zanr", typeof(string));
dt.Columns.Add("Godina Izdavanja", typeof(string));
dt.Columns.Add("Izdavacka Kuca", typeof(string));
string pomoc = "";
for (int i = 1; i < 7; i++)//OVDE TREBA MENJATI BROJ
{
for (int c = 0; c < TextBox1.Text.Length; c++)
{
if (TextBox1.Text[c] == izvodjac[i][c + 2])
{
pomoc = pomoc + TextBox1.Text[c];
}
else {
pomoc = "";
break;
}
}
if (pomoc != "")
{
dt.Rows.Add(izvodjac[i], nazivAlbuma[i], zanr[i], godinaIzdavanja[i], izdavackaKuca[i]);
}
}
Label1.Text = nazivAlbuma[1][1].ToString();
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Izvodjac", typeof(string));
dt.Columns.Add("Naziv Albuma", typeof(string));
dt.Columns.Add("Zanr", typeof(string));
dt.Columns.Add("Godina Izdavanja", typeof(string));
dt.Columns.Add("Izdavacka Kuca", typeof(string));
string pomoc = "";
for (int i = 1; i < 7; i++)
{
for (int c = 0; c < TextBox2.Text.Length; c++)
{
if (TextBox2.Text[c] == nazivAlbuma[i][c])
{
pomoc = pomoc + TextBox2.Text[c];
}
else
{
pomoc = "";
break;
}
}
if (pomoc != "")
dt.Rows.Add(izvodjac[i], nazivAlbuma[i], zanr[i], godinaIzdavanja[i], izdavackaKuca[i]);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Button5_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Izvodjac", typeof(string));
dt.Columns.Add("Naziv Albuma", typeof(string));
dt.Columns.Add("Zanr", typeof(string));
dt.Columns.Add("GodinaIzdavanja", typeof(string));
dt.Columns.Add("Izdavacka Kuca", typeof(string));
string pomoc = "";
for (int i = 1; i < 7; i++)
{
for (int c = 0; c < TextBox3.Text.Length; c++)
{
if (TextBox3.Text[c] == izdavackaKuca[i][c])
{
pomoc = pomoc + TextBox3.Text[c];
}
else
{
pomoc = "";
break;
}
}
if (pomoc != "")
dt.Rows.Add(izvodjac[i], nazivAlbuma[i], zanr[i], godinaIzdavanja[i], izdavackaKuca[i]);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Button3_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Izvodjac", typeof(string));
dt.Columns.Add("Naziv Albuma", typeof(string));
dt.Columns.Add("Zanr", typeof(string));
dt.Columns.Add("Godina Izdavanja", typeof(string));
dt.Columns.Add("Izdavacka Kuca", typeof(string));
for (int i = 0; i < 7; i++)
{
if (DropDownList1.SelectedValue == zanr[i]) {
dt.Rows.Add(izvodjac[i], nazivAlbuma[i], zanr[i], godinaIzdavanja[i], izdavackaKuca[i]);
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Button4_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Izvodjac", typeof(string));
dt.Columns.Add("NazivAlbuma", typeof(string));
dt.Columns.Add("Zanr", typeof(string));
dt.Columns.Add("Godina Izdavanja", typeof(string));
dt.Columns.Add("Izdavacka Kuca", typeof(string));
for (int i = 0; i < 7; i++)
{
if (DropDownList2.SelectedValue == godinaIzdavanja[i])
{
dt.Rows.Add(izvodjac[i], nazivAlbuma[i], zanr[i], godinaIzdavanja[i], izdavackaKuca[i]);
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
Use Split() like in the code below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"C:\temp\test.txt";
static void Main(string[] args)
{
StreamReader reader = new StreamReader(FILENAME);
string inputLine = "";
List<List<int>> data = new List<List<int>>();
while ((inputLine = reader.ReadLine()) != null)
{
string[] inputArray = inputLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (inputArray.Count() > 0)
{
List<int> numbers = inputArray.Select(x => int.Parse(x)).ToList();
data.Add(numbers);
}
}
}
}
}
Check this code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myStream As Stream = Nothing
Dim openFileDialog1 As New OpenFileDialog()
'openFileDialog1.InitialDirectory = "c:\"
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
openFileDialog1.FilterIndex = 1
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
myStream = openFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
dataFile = openFileDialog1.FileName
Label1.Text = openFileDialog1.SafeFileName
Dim myReader As New StreamReader(dataFile)
Dim line As String
line = myReader.ReadLine()
While Not (line Is Nothing)
Dim str() As String = Split(line, ControlChars.Tab)
ListView1.Items.Add(New ListViewItem(str))
line = myReader.ReadLine()
End While
myReader.Close()
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
' Check this again, since we need to make sure we didn't throw an exception on open.
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If
End Sub