WinForms DataGridView EventHandling Issues - c#

I got an issue with the event-handling in my class:
public partial class BadFiles : Form
{
private DataTable dt = new DataTable();
private string oldCellValue = string.Empty;
public BadFiles()
{
InitializeComponent();
dataGridBadFiles.EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2;
Closing += new CancelEventHandler(BadFiles_Closing);
dataGridBadFiles.CellBeginEdit += new DataGridViewCellCancelEventHandler(BadFiles_CellBeginEdit);
dataGridBadFiles.CellValueChanged += new DataGridViewCellEventHandler(BadFiles_CellValueChanged);
dataGridBadFiles.CellValidating += new DataGridViewCellValidatingEventHandler(BadFiles_CellValidating);
dt.Columns.Add("Files");
for (int i = 0; i < GlobalVars.BadFileNames.Count; i++)
{
dt.Rows.Add(Path.GetFileName(GlobalVars.BadFileNames[i]));
}
dataGridBadFiles.DataSource = dt;
}
private void BadFiles_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
oldCellValue = dataGridBadFiles[e.ColumnIndex, e.RowIndex].Value.ToString();
}
private void BadFiles_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (string.IsNullOrEmpty(e.ToString()) == true || (FileTools.CheckFileName(e.ToString()) == false))
{
e.Cancel = true;
dataGridBadFiles[e.ColumnIndex, e.RowIndex].Value = oldCellValue;
}
}
private void BadFiles_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
var newCellValue = dataGridBadFiles[e.ColumnIndex, e.RowIndex].Value.ToString();
if (FileTools.CheckFileName(newCellValue) == true)
{
var m = new string[]
{
oldCellValue,
newCellValue
};
MessageBox.Show(string.Join(Environment.NewLine, m));
}
else
{
newCellValue = oldCellValue;
MessageBox.Show("Bad Value!");
}
}
private void BadFiles_Closing(object sender, CancelEventArgs e)
{
if(FileTools.CheckFileFolder(GlobalVars.DataInput).Count != 0)
{
e.Cancel = true;
MessageBox.Show("Please rename all files in the list!", "Rename Files", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
The CellValidating event doesn't fire/work, so i tested something else with the CellValueChanged event but that isn't working either. The class shows a Form with a GridView filled from a list with bad filenames. Those filenames must be renamed from the user with a check if the new filenames are OK before changing them. The problem is that the filename checking doesn't work because of the events not firing when supposed to.

Related

there is a button and the path of the selected file is transferred to text when I save that data is not transferred to the grid

I am trying to transfer the data entered in the TextBoxes to gridcontrol. There is no problem when I write to the text manually, but I have a button on the grid, but there is a button and the path of the selected file is transferred to the text. Why would that be? How can I solve it?
I'd appreciate it if you helped.
Thank you.
public frmYazdir(TblBilgi tbl)
{
InitializeComponent();
db = new DbEntities1();
if (tbl != null)
{
tblBilgiBindingSource.DataSource = tbl;
}
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog DosyaYukle = new OpenFileDialog();
DosyaYukle.Filter = "REPX Dosyaları(*repx.*) | *.repx*";
if (DosyaYukle.ShowDialog() == DialogResult.OK)
{
filename = DosyaYukle.FileName;
textBox1.Text = filename;
if (tbl != null)
{
db.TblBilgi.Attach(tblBilgiBindingSource.DataSource as TblBilgi);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
db.SaveChanges();
MessageBox.Show("Kaydedildi.");
}
public frmYazdir(TblBilgi tbl)
{
InitializeComponent();
db = new DbEntities1();
if (tbl != null)
{
tblBilgiBindingSource.DataSource = tbl;
}
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog DosyaYukle = new OpenFileDialog();
DosyaYukle.Filter = "REPX Dosyaları(*repx.*) | *.repx*";
if (DosyaYukle.ShowDialog() == DialogResult.OK)
{
filename = DosyaYukle.FileName;
textBox1.Text = filename;
if (tbl != null)
{
db.TblBilgi.Attach(tblBilgiBindingSource.DataSource as TblBilgi);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
db.SaveChanges();
MessageBox.Show("Kaydedildi.");
}

Showing words in a text file via textbox?

My code simply reads the file, splits it into words and whows each word in the textbox with 0.1 seconds frequency.
I click to "button1" to get the file and split.
After I click Start_Button the program gets stuck. I can't see any problem in the code. Can anyone see it please?
My code is here;
public partial class Form1 : Form
{
string text1, WordToShow;
string[] WordsOfFile;
bool LoopCheck;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog BrowseFile1 = new OpenFileDialog();
BrowseFile1.Title = "Select a text file";
BrowseFile1.Filter = "Text File |*.txt";
BrowseFile1.FilterIndex = 1;
string ContainingFolder = AppDomain.CurrentDomain.BaseDirectory;
BrowseFile1.InitialDirectory = #ContainingFolder;
//BrowseFile1.InitialDirectory = #"C:\";
BrowseFile1.RestoreDirectory = true;
if (BrowseFile1.ShowDialog() == DialogResult.OK)
{
text1 = System.IO.File.ReadAllText(BrowseFile1.FileName);
WordsOfFile = text1.Split(' ');
textBox1.Text = text1;
}
}
private void Start_Button_Click(object sender, EventArgs e)
{
timer1.Interval = 100;
timer1.Enabled = true;
timer1.Start();
LoopCheck = true;
try
{
while (LoopCheck)
{
foreach (string word in WordsOfFile)
{
WordToShow = word;
Thread.Sleep(1000);
}
}
}
catch
{
Form2 ErrorPopup = new Form2();
if (ErrorPopup.ShowDialog() == DialogResult.OK)
{
ErrorPopup.Dispose();
}
}
}
private void Stop_Button_Click(object sender, EventArgs e)
{
LoopCheck = false;
timer1.Stop();
}
private void timer1_Tick(object sender, EventArgs e)
{
textBox1.Text = WordToShow;
}
}
}
Instead of Thread.Sleep(1000); use async/await feature with Task.Delay in order to keep your UI responsible:
private async void Start_Button_Click(object sender, EventArgs e)
{
timer1.Interval = 100;
timer1.Enabled = true;
timer1.Start();
LoopCheck = true;
try
{
while (LoopCheck)
{
foreach (string word in WordsOfFile)
{
WordToShow = word;
await Task.Delay(1000);
}
}
}
catch
{
Form2 ErrorPopup = new Form2();
if (ErrorPopup.ShowDialog() == DialogResult.OK)
{
ErrorPopup.Dispose();
}
}
}

Bind GridView on Button Click Event with Pagination

I'm new to asp.net and needs some help. I have a gridview with paging for every 20 records per page, I have a search button outside the gridview. What I need to do is when I click the search button, the results must be bind to gridview(which is happening now), however when the records are more than the pagesize and I need to go to the next page of the grid, the binding is lost and the binded records are the ones form the page on load event. below is my code sample.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
public void BindData()
{
{
List<EventFile> eventFile = new List<EventFile>();
eventFile = CoMailAssociationDAL.GetUploadFileUnAssigned(0, "", "", "U");
if (gvwAssociation.DataSource == null)
{
gvwAssociation.DataSource = eventFile;
gvwAssociation.DataBind();
}
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
int uFlag = 0;
string uploadFlag = this.ddlUploadDate.SelectedValue;
string fileName = this.txtSearchText.Text;
string uploadDt = this.txtDate.Text;
string status = this.ddlStatus.SelectedValue.ToString();
bt = true;
if (status == "Un-Assigned")
{
status = "U";
}
else if (status == "Assigned")
{
status = "A";
}
else
{
status = "B";
}
if ((uploadFlag == "On") && (uploadDt == ""))
{
uFlag = 0;
}
else if (uploadFlag == "On")
{
uFlag = 1;
}
else if (uploadFlag == "OnorBefore")
{
uFlag = 2;
}
else
{
uFlag = 3;
}
fileSearch = CoMailAssociationDAL.SearchFile(uFlag, fileName, uploadDt, status);
gvwAssociation.DataSource = fileSearch;
gvwAssociation.DataBind();
}
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//SaveSelectedValues();
gvwAssociation.PageIndex = e.NewPageIndex;
//BindData();
//PopulateSelectedValues();
}
First of all you should have the following event handler for paging
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvwAssociation.PageIndex = e.NewPageIndex;
bindGridWithFilter();
}
Then, move your search/ filter logic within the search button to a private method (say "bindGridWithFilter")
TIP: Try to combine both BindData and bindGridWithFilter so when there's no filter you display all records
UPDATE
Here's some refactored code for you to get an idea what I meant above.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindGridWithFilter();
}
}
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvwAssociation.PageIndex = e.NewPageIndex;
bindGridWithFilter();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
bindGridWithFilter();
}
private void bindGridWithFilter()
{
List<EventFile> eventFile = new List<EventFile>();
eventFile = CoMailAssociationDAL.GetUploadFileUnAssigned(0, "", "", "U");
if (gvwAssociation.DataSource == null)
{
// If you don't have a filter you show all records
gvwAssociation.DataSource = eventFile;
gvwAssociation.DataBind();
}
else
{
// This is same as the logic in your search button
// display only the filtered records
int uFlag = 0;
string uploadFlag = this.ddlUploadDate.SelectedValue;
string fileName = this.txtSearchText.Text;
string uploadDt = this.txtDate.Text;
string status = this.ddlStatus.SelectedValue.ToString();
bt = true;
if (status == "Un-Assigned")
{
status = "U";
}
else if (status == "Assigned")
{
status = "A";
}
else
{
status = "B";
}
if ((uploadFlag == "On") && (uploadDt == ""))
{
uFlag = 0;
}
else if (uploadFlag == "On")
{
uFlag = 1;
}
else if (uploadFlag == "OnorBefore")
{
uFlag = 2;
}
else
{
uFlag = 3;
}
List<EventFile> fileSearch = CoMailAssociationDAL.SearchFile(uFlag, fileName, uploadDt, status);
gvwAssociation.DataSource = fileSearch;
gvwAssociation.DataBind();
}
}
This should work.

Why this application is taking so much of memory?

So my problem is, i created one app for my personal use which fetch the html pages from some sites and then display it in a web browser after some alteration. Every thing is working fine but what perturbed me is the memory that it is taking. After querying for 3-4 terms, memory usage reaches to approximate 300-400 mb.
Some relevant code from the app is
void sentenceBox_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
GC.Collect();
}
HtmlDocument hd;
Word w=new Word();
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
status.Text = "Processing english req..";
if (checkInHis(queryTxt.Text))
{
sentenceBox.AllowNavigation = true;
richTextBox1.Text = w.engDefinition;
sentenceBox.DocumentText = w.engDefinition;
status.Text = "Word found in History.DONE!";
button1.Enabled = true;
return;
}
if (w == null || w.engWordProp != queryTxt.Text)
{
w.engWordProp=queryTxt.Text;
w.loadEngDefn();
w.engDefnLoadedEvent += new Word.engDefnLoaded(w_engDefnLoadedEvent);
return;
}
w.loadEngDefn();
w.engDefnLoadedEvent += new Word.engDefnLoaded(w_engDefnLoadedEvent);
}
void w_engDefnLoadedEvent(Word sender, EventArgs data)
{
sentenceBox.AllowNavigation = true;
sentenceBox.DocumentText = sender.engDefinition;
sender.engDefnLoadedEvent -= w_engDefnLoadedEvent;
button1.Enabled = true;
}
private void addToHistory(Word w)
{
status.Text = "Saving offline...";
if (!checkInHis(w.engWordProp))
{
history.Add(w);
// label1.Text = w.engWordProp + " saved in localdb. Database size: " + history.Count;
w = null;
}
else
{
// label1.Text = w.engWordProp + " Skipped. Database size: " + history.Count;
}
}
private Boolean checkInHis(string p)
{
status.Text = "checking offline storage...";
foreach (Word item in history)
{
if (item.engWordProp == p)
{
status.Text = "Word found in history.";
w = item;
return true;
}
}
status.Text = "Not found in offline database...";
return false;
}
private void sentenceBox_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
((WebBrowser)sender).AllowNavigation = false;
}
private void button2_Click_1(object sender, EventArgs e)
{
button2.Enabled = false;
status.Text = "Requesting hindi definition...";
if (checkInHis(queryTxt.Text))
{
sentenceBox.AllowNavigation = true;
sentenceBox.DocumentText = w.hindiDef;
status.Text = "DONE!";
button2.Enabled = true;
return;
}
if (w == null || w.engWordProp != queryTxt.Text)
{
w.engWordProp=queryTxt.Text;
w.loadHinDefn();
w.HindiDefLoadedEvent += new Word.hindiDefLoaded(w_HindiDefLoadedEvent);
return;
}
w.loadHinDefn();
w.HindiDefLoadedEvent += new Word.hindiDefLoaded(w_HindiDefLoadedEvent);
}
void w_HindiDefLoadedEvent(Word sender, EventArgs data)
{
sentenceBox.AllowNavigation = true;
sentenceBox.DocumentText = sender.hindiDef;
button2.Enabled = true;
sender.HindiDefLoadedEvent -= w_HindiDefLoadedEvent;
}
private void button3_Click(object sender, EventArgs e)
{
button3.Enabled = false;
saveWord(w);
button3.Enabled = true;
}
private void saveWord(Word w)
{
if (w.hindiDef == "")
{
w.loadHinDefn();
w.HindiDefLoadedEvent += new Word.hindiDefLoaded(w_HindiDefLoadedEventforHindiSave);
}
if (w.engDefinition == "")
{
w.loadEngDefn();
w.engDefnLoadedEvent += new Word.engDefnLoaded(w_engDefnLoadedEventforEnglishSave);
}
addToHistory(w);
}
void w_HindiDefLoadedEventforHindiSave(Word sender, EventArgs data)
{
sender.HindiDefLoadedEvent -= w_HindiDefLoadedEvent1;
sender.HindiDefLoadedEvent -= w_HindiDefLoadedEventforHindiSave;
}
void w_engDefnLoadedEventforEnglishSave(Word sender, EventArgs data)
{
sender.engDefnLoadedEvent -= w_engDefnLoadedEventforEnglishSave;
sender.engDefnLoadedEvent -= w_engDefnLoadedEventforEnglishSave;
}
void w_HindiDefLoadedEvent1(Word sender, EventArgs data)
{
saveWord(sender);
sender.HindiDefLoadedEvent -= w_HindiDefLoadedEvent1;
}
void w_engDefnLoadedEvent1(Word sender, EventArgs data)
{
sender.loadHinDefn();
sender.HindiDefLoadedEvent += new Word.hindiDefLoaded(w_HindiDefLoadedEvent1);
sender.engDefnLoadedEvent -= w_engDefnLoadedEvent1;
}
void initWord(String query)
{
queryTxt.Text = query;
w.engWordProp=queryTxt.Text;
w.loadEngDefn();
w.loadHinDefn();
w.engDefnLoadedEvent += new Word.engDefnLoaded(w_engDefnLoadedEvent);
w.HindiDefLoadedEvent += new Word.hindiDefLoaded(w_HindiDefLoadedEvent);
}
Word class
public Word(string q)
{
wb1 = new WebBrowser();
wb2=new WebBrowser();
engWord = q;
hindiDef = "";
engDefinition = "";
flagE = false;
flagH = false;
engUrl = "http://oxforddictionaries.com/definition/english/" + q + "?q=" + q;
hindiUrl = "http://dict.hinkhoj.com/hindi-dictionary.php?word=" + q;
wb1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted); ;
wb2.DocumentCompleted+=new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
}
public delegate void engDefnLoaded(Word sender, EventArgs data);
public event engDefnLoaded engDefnLoadedEvent;
protected void onEngDefnLoadCompleated(Word sender, EventArgs data)
{
if (engDefnLoadedEvent!=null)
{
engDefnLoadedEvent(this,data);
}
}
public void loadEngDefn()
{
if (this.engDefinition=="")
{
// wb1 = new WebBrowser();
wb1.ScriptErrorsSuppressed = true;
wb1.Url = new Uri(this.engUrl);
}
else
{
if (engDefnLoadedEvent!=null)
{
engDefnLoadedEvent(this, new EventArgs());
}
}
}
public void loadHinDefn() {
if (this.hindiDef=="")
{
// wb2 = new WebBrowser();
wb2.ScriptErrorsSuppressed = true;
wb2.Url = new Uri(this.hindiUrl);
}
else
{
if (HindiDefLoadedEvent!=null)
{
HindiDefLoadedEvent(this, new EventArgs());
}
}
}
[NonSerialized]
HtmlDocument hd;
void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (((WebBrowser)sender).ReadyState == WebBrowserReadyState.Complete)
{
hd = ((WebBrowser)sender).Document;
if (e.Url.ToString() == this.hindiUrl)
{
parsePage(hd.GetElementById("maint"), "hindi");
((WebBrowser)sender).DocumentCompleted -= wb_DocumentCompleted;
sender = null;
}
else
{
parsePage(hd.GetElementById("entryPageContent"), "eng");
((WebBrowser)sender).DocumentCompleted -= wb_DocumentCompleted;
sender = null;
}
}
}
private void parsePage(HtmlElement hd, string lan)
{
HtmlElementCollection he;
if (lan == "eng")
{
he = hd.GetElementsByTagName("section");
foreach (HtmlElement item in he)
{
this.engDefinition += item.InnerHtml + "<br>";
}
flagE = true;
engDefnLoadedEvent(this, new EventArgs());
wb1 = null;
wb1.Dispose();
return;
}
else
{
he = hd.GetElementsByTagName("div");
foreach (HtmlElement item in he)
{
if (item.GetAttribute("itemprop") == "itemListElement")
{
this.hindiDef += item.GetElementsByTagName("div")[0].InnerHtml + "<br>";
}
}
flagH = true;
HindiDefLoadedEvent(this,new EventArgs());
wb2 = null;
wb2.Dispose();
return;
}
}
Question: How to remove this memory leak issue ?
sample pic
After query 25 words.
First I'd like to point out that just because your application uses 300 - 400 MB of memory doesn't necessarily mean that you have a memory leak. Only if the memory keeps increasing with each requested page and is never released do you have a leak.
Second, in order to diagnose the problem you need to run a memory profiler. If you are using the Premium or Ultimate edition of Visual Studio, it has a memory profile feature. If not you can use either RedGate Memory Profile (14-day free trial) or similar software.
I would also add that the most common cause for leaks in .NET is the use of events where a short lived object attaches itself as an observer/handler to an event raised by a long lived object.
Well in the constructor of your Word class you have the following code:
wb1 = new WebBrowser();
wb2=new WebBrowser();
The WebBrowser class does is to instantiate some of the web browsing features of your local IE version.My guess is that WebBrowser being a part of the IE it has a high memory consumption.So imagine that you instantiate 2 WebBrowser objects for each word that you have.You could use a pool system for your WebBrowser objects, but i would replace the behavior of those with an WebClient object which is disposable.
P.S. The Garbage Collector system is a fine tuned system using GC.Collect(); it's like using a sledgehammer on your code.

When a combobox is chosen a openFileDialog must appear

I have made a method so that when you click on Browse From File the openDialogBox appear. But it does not . What is wrong ?
This is the method that I made to Open the OpenFileDialog:
public void Lista()
{
string[] col2 = new string[dataGridView1.Rows.Count];
for (int i = 0; i < dataGridView1.Rows.Count; i++)
if (col2[i] == "Browse From File...")
{
DialogResult result2 = openFileDialog2.ShowDialog();
if (result2 == DialogResult.OK)
{
// filename = openFileDialog1.FileName;
}
}
}
This is the method where I call the method Lista.
private void button1_Click(object sender, EventArgs e)
{
// opens window **BROWSE**
openFileDialog1.Title = "Choose File CSV ";
string filename = "";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
filename = openFileDialog1.FileName;
textBox1.Text = filename;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(textBox1.Text);
stringforData = file.ReadLine();
while ((line = file.ReadLine()) != null)
{
//read inside the table
fileList.Add(line.Split(';'));
}
file.Close();
this.ToDataGrid();
this.Lista();
}
}
DataGridView by only having one editing control for all the rows. Here's how I handled a similar situation, First try a delegate to the EditControlShowing event
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OpenFileDialog ofd = new OpenFileDialog();
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Columns.Add("ID", "Product ID");
DataGridViewComboBoxColumn comboxboxCol = new DataGridViewComboBoxColumn();
comboxboxCol.HeaderText = "Type";
comboxboxCol.Items.Add("Obj1");
comboxboxCol.Items.Add("Obj2");
comboxboxCol.Items.Add("Obj3");
dataGridView1.Columns.Add(comboxboxCol);
dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(Grid_EditingControlShowing);
}
void Grid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox combo = e.Control as ComboBox;
if (combo != null)
{
// the event to handle combo changes
EventHandler comboDelegate = new EventHandler(
(cbSender, args) =>
{
ofd.ShowDialog();
});
// register the event with the editing control
combo.SelectedValueChanged += comboDelegate;
}
}
}
}
Hope this will solve your Issue

Categories