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
enter image description here
namespace Implementer
{
public partial class MainForm : Form
{
#region intit and globals
public MainForm()
{
InitializeComponent();
DevExpress.XtraGrid.Views.Grid.GridView gridView = new DevExpress.XtraGrid.Views.Grid.GridView();
var transactions = new ObservableCollection<Item>();
for (int i = 0; i <= 100; i++)
{
transactions.Add(new Item { Content = "Item " + i });
}
grdTransactions.AllowDrop = true;
grdTransactions.DataSource = transactions;
dgmWf.AddingNewItem += (s, e) => transactions.Remove(e.Item.Tag as Item);
}
Point mouseDownLocation;
GridHitInfo gridHitInfo;
#endregion
#region events
public void Mainform_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'vA_ERP4_ADMINDataSet.SYSTEM_MODULES' table. You can move, or remove it, as needed.
//Project initiation
//Fill drop down for project list
cmbProject.SelectedIndex = 0;
DataAccess dataAccess = new DataAccess(GlobalFunctions.GetConnectionString());
DataTable dtResult = dataAccess.ExecuteQueryDataSet("select MODULE_CODE, MODULE_DESC from SYSTEM_MODULES where module_is_active=1").Tables[0];
cmbProject.DisplayMember = "MODULE_DESC";
cmbProject.ValueMember = "MODULE_CODE";
cmbProject.DataSource = dtResult;
}
private void cmbProject_SelectedIndexChanged(object sender, EventArgs e)
{
lblCurrentProject.Text = cmbProject.Text;
if (cmbProject.Text != null)
{
DataAccess dataAccess = new DataAccess(GlobalFunctions.GetConnectionString());
DataTable dtTransactions = dataAccess.ExecuteQueryDataSet("select sys_trans_id, sys_trans_desc1 from WF_SYSTEM_TRANS where MODULE_CODE= '" + cmbProject.Text + "'").Tables[0];
grdTransactions.DataSource = dtTransactions;
}
}
private void btnSalesInvoice_Click(object sender, EventArgs e)
{
int sysTransId = 1001;
FillTransactionDetails(sysTransId);
}
#endregion
#region drag drop
private void grdTransactions_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && CanStartDragDrop(e.Location))
{
StartDragDrop();
}
}
private void grdTransactions_MouseDown(object sender, MouseEventArgs e)
{
gridHitInfo = grdVTransactions.CalcHitInfo(e.Location);
mouseDownLocation = e.Location;
}
private void grdTransactions_MouseLeave(object sender, EventArgs e)
{
if (gridHitInfo != null)
gridHitInfo.View.ResetCursor();
gridHitInfo = null;
}
private bool CanStartDragDrop(Point location)
{
return gridHitInfo.InDataRow && (Math.Abs(location.X - mouseDownLocation.X) > 2 || Math.Abs(location.Y - mouseDownLocation.Y) > 2);
}
public void StartDragDrop()
{
var draggedRow = gridHitInfo.View.GetRow(gridHitInfo.RowHandle) as Item;
var tool = new FactoryItemTool(" ", () => " ", diagram => new DiagramShape(BasicShapes.Rectangle) { Content = draggedRow.Content, Tag = draggedRow }, new System.Windows.Size(150, 100), false);
dgmWf.Commands.Execute(DiagramCommandsBase.StartDragToolCommand, tool, null);
}
#endregion
#region function
private void FillTransactionDetails(int systemTransactionId)
{
//Fill document
//Fill steps
DataAccess dataAccess = new DataAccess(GlobalFunctions.GetConnectionString());
DataTable transactionDetails = dataAccess.ExecuteQueryDataSet("SELECT DOC_TYPE_DESC1 FROM WF_SYSTEM_TRANS_DT WHERE SYS_TRANS_ID=1001 and MODULE_CODE= '" + cmbProject.Text + "'").Tables[0];
transactionDetails.Rows.Add();
grdDocuments.DataSource = transactionDetails;
grdDocuments.Columns["Details"].DisplayIndex = 2;
grdDocuments.Columns["Delete"].DisplayIndex = 2;
DataTable transactionSteps = dataAccess.ExecuteQueryDataSet("select WF_STEP_DESC1 from WF_STEPS where wf_id= 10101 and MODULE_CODE= '" + cmbProject.Text + "'").Tables[0];
transactionSteps.Rows.Add();
grdSteps.DataSource = transactionSteps;
}
#endregion
}
public class Item
{
public string Content { get; set; }
}
}
I don't really know where is the mistake and have been looking at it for the past few days and searching for an answer but no luck so I'd be so happy if you could help me out. It was working without the data fetching. but after calling the data it doesn't work. drag it from the grid view and when it reaches the diagram control it would turn into a rectangle with a tag property of it's ID.. With regards to the connection string.. I created a global function to just call it on the main form.
So, I'm creating a program to check names of a client. But I get this error.
"No row can be added to a DataGridView control that does not have columns. Columns must be added first.'"
I'm unsure of what to do at this point, as it's all coded correctly. and I just, I don't understand why it's not working. A friend of mine is running the EXACT same code, and his build worked flawlessly.
Here's my code.
private void PopulateDataGrideView(string Name, string Status)
{
if (base.InvokeRequired)
{
base.BeginInvoke(new MethodInvoker(() => {
DataGridViewRow dataGridViewRow = new DataGridViewRow();
if (Status == "Yes")
{
dataGridViewRow.DefaultCellStyle.BackColor = Color.LightGreen;
Status = "Name Available";
}
else if (Status == "No")
{
dataGridViewRow.DefaultCellStyle.BackColor = Color.Red;
Status = "Not Available";
if (this.VisibilityBx.Checked)
{
dataGridViewRow.Visible = false;
}
}
dataGridViewRow.CreateCells(this.checkedNames, new object[] { Name, Status });
this.checkedNames.Rows.Add(dataGridViewRow);
if (scrollBx.Checked)
{
this.checkedNames.FirstDisplayedScrollingRowIndex = this.checkedNames.RowCount - 1;
}
this.progressBar1.Increment(1);
}));
}
}
private void saveAvailableNamesToolStripMenuItem_Click(object sender, EventArgs e)
{
List<string> strs = new List<string>();
if (this.checkedNames.Rows.Count > 0)
{
foreach (DataGridViewRow row in (IEnumerable)this.checkedNames.Rows)
{
if (row.Cells[1].Value.Equals("Name Available"))
{
strs.Add(row.Cells[0].Value.ToString());
}
}
if (strs.Count > 0)
{
string currentDirectory = Environment.CurrentDirectory;
DateTime now = DateTime.Now;
File.WriteAllLines(string.Concat(currentDirectory, "\\Available Names ", now.ToString("dd-MM-yyyy HH.mm.ss tt"), ".txt"), strs);
}
}
}
private void saveTakenNamesToolStripMenuItem_Click(object sender, EventArgs e)
{
List<string> strs = new List<string>();
if (this.checkedNames.Rows.Count > 0)
{
foreach (DataGridViewRow row in (IEnumerable)this.checkedNames.Rows)
{
if (row.Cells[1].Value.Equals("Not Available"))
{
strs.Add(row.Cells[0].Value.ToString());
}
}
if (strs.Count > 0)
{
string currentDirectory = Environment.CurrentDirectory;
DateTime now = DateTime.Now;
File.WriteAllLines(string.Concat(currentDirectory, "\\Taken Names ", now.ToString("dd-MM-yyyy HH.mm.ss tt"), ".txt"), strs);
}
}
}
private void scrollBx_CheckedChanged(object sender, EventArgs e)
{
if (this.checkedNames.RowCount > 0)
{
if (this.scrollBx.Checked)
{
this.checkedNames.FirstDisplayedScrollingRowIndex = this.checkedNames.RowCount - 1;
}
else if (!this.scrollBx.Checked)
{
this.checkedNames.FirstDisplayedScrollingRowIndex = 0;
}
}
}
private void VisibilityBx_CheckedChanged(object sender, EventArgs e)
{
if (this.checkedNames.Rows.Count > 0)
{
foreach (DataGridViewRow row in (IEnumerable)this.checkedNames.Rows)
{
if (!this.VisibilityBx.Checked)
{
if (!row.Visible)
{
row.Visible = true;
}
}
else if (this.VisibilityBx.Checked)
{
if ((string)row.Cells[1].Value == "Not Available")
{
row.Visible = false;
}
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void CheckedNames_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
Use:
DataGridViewRow row = (DataGridViewRow)YOURDATAGRIDVIEW.Rows[0].Clone();
to create a new row to be added, instead of:
DataGridViewRow dataGridViewRow = new DataGridViewRow();
This preserves the column names in the new row.
You should no longer need this line of code:
dataGridViewRow.CreateCells(this.checkedNames, new object[] { Name, Status });
Also ensure that data grid view has columns, which is an often cause of this error.
I have 2 buttons that is supposed to update the db, and when it updates the page should do a postback with the updated info, however...right now it updates in db alright, but the page doesnt update until the 2nd click, and then the clicks afterwards are alright until i clicked on anohter tab...everything happens all over again...btw the buttons are called up and down, they are dynamically created inside a template that creates the grid
so the up/down button is built right after page_load, the page_load function calls the loaddisplaygrid(or loaddynamicdisplaygrid), then in the loaddisplaygrid(or loaddynamicdisplaygrid) function it builds the template that build the buttons
//page load
protected void Page_Load(object sender, EventArgs e)
{
RadToolBarItem textbxItem = MainRadToolBar.Items.FindItemByText("textbox");
RadTextBox displayName = (RadTextBox)textbxItem.FindControl("displayName");
Session["UserID"] = getUserID();
if (!Page.IsPostBack)
{
if (Profile.ShowFilter)
{
displayMenuBar.Style["display"] = "block";
displayLineBreak.Style["display"] = "block";
}
else
{
displayMenuBar.Style["display"] = "none";
displayLineBreak.Style["display"] = "none";
}
loadDisplay();
loadTemplate();
loadTabs();
saveDefaultOneOffFilter();
checkIfEmpty();
RadTab tab = displayTabs.SelectedTab;
Profile.CurrTemplate = Profile.DefaultTemplate;
if (Profile.DefaultTemplate == dfltTempID) //new user
{
displayName.Text = User.Identity.Name + "_default";
si_display_save_button_Click();
setDefault();
Profile.CurrTemplate = Profile.DefaultTemplate;
updateStatsformat();
Response.Redirect("Display.aspx");
}
if (tab != null)
{
loadDisplayGrid(Profile.CurrTemplate);
Session["SelectedTabID"] = tab.Text;
}
}
else
{
RadTab tab = displayTabs.SelectedTab;
if (tab != null)
{
if (tab.Text == Session["SelectedTabID"].ToString())
{
//ScriptManager.RegisterStartupScript(this, typeof(Page), "Alert", "<script>alert('" + "a" + "');</script>", false);
loadDynamicDisplayGrid(Profile.CurrTemplate);//needs to be different, special just for postback
}
else
{
loadDisplayGrid(Profile.CurrTemplate);
Session["SelectedTabID"] = displayTabs.SelectedTab.Text;
}
//automatically saves when toolbar is not visible....
if (!Profile.ShowFilter) { si_display_save_button_Click(); }
}
}
}
/// <summary>
/// updates and loads the RadGrid for the Display page, depending on which Tab is selected
/// </summary>
private void loadDisplayGrid(int tmpid)
{
short DType = Convert.ToInt16(displayTabs.SelectedTab.Value);
GridBoundColumn column;
GridColumn columnchkbx;
GridButtonColumn columnUp;
GridButtonColumn columnDown;
GridTemplateColumn columntxtbx;
DisplayGrid.DisplayGridDataTable DisplayGridDT = new DisplayGrid.DisplayGridDataTable();
DisplayGridTableAdapters.DisplayGridTableAdapter DisplayGridTA = new DisplayGridTableAdapters.DisplayGridTableAdapter();
//update statsformat for the user if necessary
if (Profile.CurrTemplate != 0)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["testDB_ConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("UpdateNewStat", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#userid", SqlDbType.UniqueIdentifier).Value = getUserID();
command.Parameters.Add("#tempid", SqlDbType.SmallInt).Value = Profile.CurrTemplate;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
//ScriptManager.RegisterStartupScript(this, typeof(Page), "Alert", "<script>alert('" + Profile.CurrTemplate + "');</script>", false);
if (Profile.DefaultTemplate != 0)
{
DisplayGridTA.FillBy(DisplayGridDT, DType, (short)tmpid);
}
if (DisplayGridDT.Rows.Count == 0)
{
DisplayGridTA.Fill(DisplayGridDT, getUserID(), DType);
}
StatsFormatGrid.Columns.Clear();
//Stat IsDisplayed
columnchkbx = new GridCheckBoxColumn();
columnchkbx.HeaderText = "Displayed";
columnchkbx.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnchkbx);
//Stats Name
column = new GridBoundColumn();
column.HeaderText = "Stats Name";
column.DataField = DisplayGridDT.Columns[0].ColumnName;
column.UniqueName = DisplayGridDT.Columns[0].ColumnName;
StatsFormatGrid.Columns.Add(column);
//Invisible columns
for (int i = 3; i <= 6; i++)
{
column = new GridBoundColumn();
column.HeaderText = (i == 3) ? "StatsTable.Stats_id" : (i == 4) ? "StatsTable.StatsValue_Type" : (i == 5) ? "StatsTable.Stats_CHeader" : "StatsTable.Stats_Desc";
column.DataField = DisplayGridDT.Columns[i].ColumnName;
column.UniqueName = DisplayGridDT.Columns[i].ColumnName;
column.Visible = false;
StatsFormatGrid.Columns.Add(column);
}
//Dynamically created column - Stats Display Format
columntxtbx = new GridTemplateColumn();
columntxtbx.HeaderText = "Stats Display Format";
columntxtbx.ItemTemplate = new MyTemplate(DisplayGridDT, getUserID(),Profile.CurrTemplate);
StatsFormatGrid.Columns.Add(columntxtbx);
/*
columnArrow = new GridTemplateColumn();
columnArrow.ItemTemplate = new ArrowTemplate(DisplayGridDT, getUserID(), Profile.CurrTemplate);
StatsFormatGrid.Columns.Add(columnArrow);*/
columnUp = new GridButtonColumn();
columnUp.Text = "↑";
columnUp.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnUp);
columnDown = new GridButtonColumn();
columnDown.Text = "↓";
columnDown.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnDown);
StatsFormatGrid.DataSource = DisplayGridDT;
StatsFormatGrid.DataBind();
foreach (GridDataItem item in StatsFormatGrid.Items) //sets the properties of IsDisplayed
{
DataRowView row = (DataRowView)item.DataItem;
CheckBox chkbx = (CheckBox)item["IsDisplayed"].Controls[0];
chkbx.Enabled = true;
chkbx.AutoPostBack = true;
String value = row["IsDisplayed"].ToString();
chkbx.Checked = (value == "True");
}
}
/// <summary>
/// This is the template for GridTemplateColumn in the display page's grid
/// This represent the column DisplayString
/// Three different kinds of contents are used in each cell of the column depending on StatsValue_Type
/// </summary>
private class MyTemplate : ITemplate
{
//protected RequiredFieldValidator validator1;
//protected RangeValidator validator2;
protected TextBox textBox;
protected DropDownList ddList;
protected Label txtlb;
protected Button up;
protected Button down;
private DisplayGrid.DisplayGridDataTable MyDT = new DisplayGrid.DisplayGridDataTable();
private DisplayGridTableAdapters.DisplayGridTableAdapter MyTA = new DisplayGridTableAdapters.DisplayGridTableAdapter();
private Guid myUserID = new Guid();
private int template;
public MyTemplate(DisplayGrid.DisplayGridDataTable DGDT, Guid UserID,int tempid)
{
MyDT = DGDT;
myUserID = UserID;
template = tempid;
}
public void InstantiateIn(System.Web.UI.Control container)
{
//textBox = new TextBox();
ddList = new DropDownList();
txtlb = new Label();
up = new Button();
up.Text = "↑";
down = new Button();
down.Text = "↓";
//textBox.ID = "templateColumnTextBox";
ddList.ID = "templateColumnDDList";
txtlb.ID = "txtLabel";
up.ID = "up";
down.ID = "down";
//textBox.DataBinding += new EventHandler(textBox_DataBinding);
ddList.DataBinding += new EventHandler(ddList_DataBinding);
txtlb.DataBinding += new EventHandler(label_DataBinding);
up.Click += new EventHandler(up_Click);
down.Click += new EventHandler(down_Click);
/*validator1 = new RequiredFieldValidator();
validator1.ControlToValidate = "templateColumnTextBox";
validator1.ErrorMessage = "*";
validator1.Display = ValidatorDisplay.Dynamic;
validator2 = new RangeValidator();
validator2.ControlToValidate = "templateColumnTextBox";
validator2.Type = ValidationDataType.Integer;
validator2.MinimumValue = "0";
validator2.MaximumValue = "12";
validator2.ErrorMessage = "*0-12";
validator2.Display = ValidatorDisplay.Dynamic;*/
//container.Controls.Add(textBox);
container.Controls.Add(ddList);
container.Controls.Add(txtlb);
container.Controls.Add(up);
container.Controls.Add(down);
//container.Controls.Add(validator1);
//container.Controls.Add(validator2);
}
/// <summary>
/// Generates the text boxes when StatsValue_Type is double or percentage
/// Assigns the text and the style
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/*protected void textBox_DataBinding(object sender, EventArgs e)
{
TextBox tBox = (TextBox)sender;
GridDataItem container = (GridDataItem)tBox.NamingContainer;
string displayStr = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string valType = ((DataRowView)container.DataItem)[MyDT.Columns[4].ColumnName].ToString();
string rdm = ((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString();
if (valType == "double" || valType == "percentage")
{
tBox.Text = displayStr.Remove(displayStr.IndexOf(" "));
tBox.Font.Bold = true;
tBox.Style["text-align"] = "center";
tBox.Width = 70;
tBox.AutoPostBack = true;
//tBox.TextChanged += new EventHandler(DisplayTextBox_TextChanged);
}
else
{
tBox.Enabled = false;
tBox.Visible = false;
}
}*/
protected void up_Click(object sender, EventArgs e)
{
Button bt = (Button)sender;
GridDataItem container = (GridDataItem)bt.NamingContainer;
string displayStr = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string valType = ((DataRowView)container.DataItem)[MyDT.Columns[4].ColumnName].ToString();
string rdm = ((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString();
int num = Convert.ToInt32(displayStr.Substring(0, displayStr.IndexOf(' ')))+1;
string updateDisplay = num.ToString() + " decimals";
string updateVal = "{0:f" + num.ToString() + "}";
short stats_id = Convert.ToInt16(rdm);
if (num < 13 && num > -1)
{
MyTA.UpdateQuery(updateVal, updateDisplay, stats_id, (short)template);
}
}
protected void down_Click(object sender, EventArgs e)
{
Button bt = (Button)sender;
GridDataItem container = (GridDataItem)bt.NamingContainer;
//ScriptManager.RegisterStartupScript(bt, typeof(Page), "Alert", "<script>alert('" + "a" + "');</script>", false);
string displayStr = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string valType = ((DataRowView)container.DataItem)[MyDT.Columns[4].ColumnName].ToString();
string rdm = ((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString();
int num = Convert.ToInt32(displayStr.Substring(0, displayStr.IndexOf(' '))) -1;
string updateDisplay = num.ToString() + " decimals";
string updateVal = "{0:f" + num.ToString() + "}";
short stats_id = Convert.ToInt16(rdm);
if (num < 13 && num > -1)
{
MyTA.UpdateQuery(updateVal, updateDisplay, stats_id, (short)template);
}
}
/// <summary>
/// Generates the drop down lists when StatsValue_Type is Date
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void ddList_DataBinding(object sender, EventArgs e)
{
DropDownList dl = (DropDownList)sender;
GridDataItem container = (GridDataItem)dl.NamingContainer;
string displayStr = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string valType = ((DataRowView)container.DataItem)[MyDT.Columns[4].ColumnName].ToString();
string rdm = ((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString();
if (valType == "Date")
{
dl.Items.Add(new ListItem("MM-DD-YY", "{0:MM-dd-yy}"));
dl.Items.Add(new ListItem("DD-MM-YY", "{0:dd-MM-yy}"));
dl.Items.Add(new ListItem("DD-MMM-YYYY", "{0:dd-MMM-yyyy}"));
dl.SelectedIndex = (displayStr == "MM-DD-YY") ? 0 : (displayStr == "DD-MM-YY") ? 1 : 2;
dl.AutoPostBack = true;
dl.SelectedIndexChanged += new EventHandler(DisplayDDList_IndexChanged);
up.Visible = false;
down.Visible=false;
}
/*else if (valType == "double" || valType == "percentage")
{
dl.Items.Add(new ListItem("1 decimals", "{0:f1}"));
dl.Items.Add(new ListItem("2 decimals", "{0:f2}"));
dl.Items.Add(new ListItem("3 decimals", "{0:f3}"));
dl.Items.Add(new ListItem("4 decimals", "{0:f4}"));
dl.Items.Add(new ListItem("5 decimals", "{0:f5}"));
dl.Items.Add(new ListItem("6 decimals", "{0:f6}"));
dl.Items.Add(new ListItem("7 decimals", "{0:f7}"));
dl.Items.Add(new ListItem("8 decimals", "{0:f8}"));
dl.Items.Add(new ListItem("9 decimals", "{0:f9}"));
dl.Items.Add(new ListItem("10 decimals", "{0:f10}"));
dl.Items.Add(new ListItem("11 decimals", "{0:f11}"));
dl.Items.Add(new ListItem("12 decimals", "{0:f12}"));
dl.SelectedIndex =Convert.ToInt32(displayStr.Substring(0, displayStr.IndexOf(' ')));
dl.AutoPostBack = true;
dl.SelectedIndexChanged += new EventHandler(DisplayDDList_IndexChanged);
}*/
else
{
dl.Enabled = false;
dl.Visible = false;
}
}
/// <summary>
/// Generates the words " digits" after the textboxes when StatsValue_Type is double or percentage
/// Generates the label with text of DisplayString when StatsValue_Type is bit
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void label_DataBinding(object sender, EventArgs e)
{
Label lbl = (Label)sender;
GridDataItem container = (GridDataItem)lbl.NamingContainer;
string displayStr = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string valType = ((DataRowView)container.DataItem)[MyDT.Columns[4].ColumnName].ToString();
string rdm = ((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString();
if (valType == "bit")
{
lbl.Text = displayStr;
lbl.Font.Bold = true;
up.Visible = false;
down.Visible = false;
}
else if (valType == "double" || valType == "percentage") {
lbl.Text = displayStr;
lbl.Font.Bold = true;
}
else { lbl.Text = ""; }
}
/// <summary>
/// Handles the event when textbox is sumbitted
/// inefficient at the moment because it is fired for every textbox every tab change
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/*protected void DisplayTextBox_TextChanged(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
GridDataItem container = (GridDataItem)tb.NamingContainer;
string textCur = ((TextBox)sender).Text + " decimals";
string textOld = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string testing = ((DataRowView)container.DataItem)[MyDT.Columns[0].ColumnName].ToString();
if (textCur != textOld)
{
int value = Convert.ToInt16(((TextBox)sender).Text);
short stats_id = Convert.ToInt16(((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString());
string format = "{0:f" + value.ToString() + "}";
string text = value.ToString() + " decimals";
ScriptManager.RegisterStartupScript(tb, typeof(Page), "Alert", "<script>alert('" + "a" + "');</script>", false);
//MyTA.UpdateDisplayGrid(format, text, myUserID, stats_id);
MyTA.UpdateQuery(format, text, stats_id, (short)template);
}
}*/
/// <summary>
/// Handles the event when dropdownlist selection changes
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void DisplayDDList_IndexChanged(object sender, EventArgs e)
{
string date = ((DropDownList)sender).SelectedItem.Text;
string format = ((DropDownList)sender).SelectedItem.Value;
DropDownList ddl = (DropDownList)sender;
GridDataItem container = (GridDataItem)ddl.NamingContainer;
short stats_id = Convert.ToInt16(((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString());
//MyTA.UpdateDisplayGrid(format, date, myUserID, stats_id);
MyTA.UpdateQuery(format, date, stats_id, (short)template);
}
}
//this is called on postback
protected void loadDynamicDisplayGrid(int tmpid)
{
ArrayList oldchkbxList = new ArrayList();
short DType = Convert.ToInt16(displayTabs.SelectedTab.Value);
GridBoundColumn column;
GridColumn columnchkbx;
GridTemplateColumn columntxtbx;
GridButtonColumn columnUp;
GridButtonColumn columnDown;
//GridTemplateColumn columnArrow;
DisplayGrid.DisplayGridDataTable DisplayGridDT = new DisplayGrid.DisplayGridDataTable();
DisplayGridTableAdapters.DisplayGridTableAdapter DisplayGridTA = new DisplayGridTableAdapters.DisplayGridTableAdapter();
//update statsformat for the user if necessary
if (Profile.CurrTemplate != 0)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["testDB_ConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("UpdateNewStat", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#userid", SqlDbType.UniqueIdentifier).Value = getUserID();
command.Parameters.Add("#tempid", SqlDbType.SmallInt).Value = Profile.CurrTemplate;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
if (Profile.DefaultTemplate != 0)
{
DisplayGridTA.FillBy(DisplayGridDT, DType, (short)tmpid);
}
if (DisplayGridDT.Rows.Count == 0)
{
DisplayGridTA.Fill(DisplayGridDT, getUserID(), DType);
}
//save the old values of the IsDisplayed checkboxes before refresh
foreach (GridDataItem item in StatsFormatGrid.Items)
{
CheckBox chkbx = (CheckBox)item["IsDisplayed"].Controls[0];
oldchkbxList.Add(chkbx.Checked);
}
StatsFormatGrid.Columns.Clear();
//Stat IsDisplayed
columnchkbx = new GridCheckBoxColumn();
columnchkbx.HeaderText = "Displayed";
columnchkbx.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnchkbx);
//Stats Name
column = new GridBoundColumn();
column.HeaderText = "Stats Name";
column.DataField = DisplayGridDT.Columns[0].ColumnName;
column.UniqueName = DisplayGridDT.Columns[0].ColumnName;
StatsFormatGrid.Columns.Add(column);
//Invisible columns
for (int i = 3; i <= 6; i++)
{
column = new GridBoundColumn();
column.HeaderText = (i == 3) ? "StatsTable.Stats_id" : (i == 4) ? "StatsTable.StatsValue_Type" : (i == 5) ? "StatsTable.Stats_CHeader" : "StatsTable.Stats_Desc";
column.DataField = DisplayGridDT.Columns[i].ColumnName;
column.UniqueName = DisplayGridDT.Columns[i].ColumnName;
column.Visible = false;
StatsFormatGrid.Columns.Add(column);
}
//Dynamically created column - Stats Display Format
columntxtbx = new GridTemplateColumn();
columntxtbx.HeaderText = "Stats Display Format";
columntxtbx.ItemTemplate = new MyTemplate(DisplayGridDT, getUserID(),Profile.CurrTemplate);
StatsFormatGrid.Columns.Add(columntxtbx);
/*
columnArrow = new GridTemplateColumn();
columnArrow.ItemTemplate = new ArrowTemplate(DisplayGridDT, getUserID(), Profile.CurrTemplate);
StatsFormatGrid.Columns.Add(columnArrow);*/
columnUp = new GridButtonColumn();
columnUp.Text = "↑";
columnUp.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnUp);
columnDown = new GridButtonColumn();
columnDown.Text = "↓";
columnDown.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnDown);
StatsFormatGrid.DataSource = DisplayGridDT;
StatsFormatGrid.DataBind();
int itr = 0;
foreach (GridDataItem item in StatsFormatGrid.Items) //sets the properties of IsDisplayed
{
CheckBox chkbx = (CheckBox)item["IsDisplayed"].Controls[0];
chkbx.Enabled = true;
chkbx.AutoPostBack = true;
chkbx.Checked = (Boolean)oldchkbxList[itr];
DataRowView row = (DataRowView)item.DataItem;
String value = row["IsDisplayed"].ToString();
if (value == "True" && !(Boolean)oldchkbxList[itr])
{
DisplayedCheckbox_CheckedChanged(chkbx, DisplayGridDT);
}
else if (value != "True" && (Boolean)oldchkbxList[itr])
{
DisplayedCheckbox_CheckedChanged(chkbx, DisplayGridDT);
}
itr++;
}
}
//this is html
<telerik:RadGrid ID="StatsFormatGrid" runat="server" AutoGenerateColumns="False" GridLines="None"
OnDataBound="grid_data_bound" EnableAJAX="true">
<%--ClientSettings>
<Selecting AllowRowSelect="True"></Selecting>
</ClientSettings--%>
</telerik:RadGrid>
I believe you are having a common problem with databinding and the ASP.net Page life cycle. Simply put: you first databind the data and then you change it. The Page_Load event handler binds your data, after that the press of the button is handled and it changes the database. However, the control is already bound to a previous version of the data and displays old information.
You should databind your control AFTER the button press has been handled and the change in the database has been processed. Try putting your databinding code in the Page_PreRender event handler.
You can add
Response.Redirect(Request.RawUrl);
after finish updating database in button click event.
Or call functions that init data in your page. For example
private void Page_Load(...)
{
if(!Page.IsPostBack)
{
InitData();
}
}
private void InitData()
{
//Do init data control in your page
// For exp: binding the grid, combo box....
}
protected void btn_Update_Clicked(...)
{
//1. Update database
//2. Call InitData() function to reload data from database
}
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