break
Apr 24

Have you ever come across something like this? I had, and I thought it was something interesting to write about.

The scenario:
I was using the AJAX AutoCompleteExtender when I realized that inside the ServiceMethod of my AutoCompleteExtender, I needed to call a method that needed between it’s parameters an Enum.

To the ServiceMethod of an AutoCompleteExtender, you can pass parameters through the contextKey. Nonetheless I couldn’t pass an enum, so I decided to pass the name of the Database as an string, and then inside the ServiceMethod convert the string into an enum.

Anyways, this is how you convert a string into an enum:

private void Form1_Load(object sender, EventArgs e)
{
DataBase db = convertStringToEnum("Pubs");
MessageBox.Show(db.ToString());
}
private DataBase convertStringToEnum(string dbName)
{
return (DataBase)Enum.Parse(typeof(DataBase), dbName);
}
public enum DataBase
{
Northwind = 0,
Pubs = 1
}

If you have any questions, feel free to leave a comment.

Dec 19

Another easy but useful task: Read the names of different folders that are inside a directory. Reading the names is easy, but splitting the absolute path of the directory to only get the name of the folder, is a little bit more interesting.

I am using ASP.NET to do this:

Default.aspx

<form id=”form1″ runat=”server”>
<asp:listbox id=”ListBox1″ runat=”server”></asp:listbox>
</form>

I just declare a listbox inside the form.

Default.aspx.cs

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
foreach (string subDirectory in
System.IO.Directory.GetDirectories(
AppDomain.CurrentDomain.BaseDirectory))
{
// split the folders into an array of strings
string[] directory = subDirectory.Split(new char[] { '\\' });
// how many folders do we have?
int numOfDirectories = directory.Length;
// the last folder is the folder we are looking for
ListBox1.Items.Add(directory[numOfDirectories - 1]);
}
}
}

System.IO.Directory.GetDirectories as MSDN states: “Gets the names of subdirectories in the specified directory”. However, you get an absolute path of the directory.

If you would like to add the name of the folder to a listbox you will need to split the string that contains the different directories and store the directories in an array of strings:

string[] directory = subDirectory.Split(new char[] { ‘\\’ });

After this step, you get the amount of directories the absolute path has, and then look for the last directory in the array:

int numOfDirectories = directory.Length;
ListBox1.Items.Add(directory[numOfDirectories - 1]);

The directory I am using to read the files is AppDomain.CurrentDomain.BaseDirectory which is the base directory that the assembly resolver uses to search for assemblies.

The result of this snippet is:

Dec 18

The task: You have a string that is comma delimited , and you would like to sort that string and display it in a listbox.

I am using ASP.NET to do this:

Default.aspx

<form id=”form1″ runat=”server”>
<asp:listbox id=”ListBox1″ runat=”server”></asp:listbox>
</form>

I just declare a listbox inside the form.

Default.aspx.cs

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// the comma delimited list
string names = "Lesseps,Daniel,Isaacs,Diaz";
// split the string and make it an array of strings
string[] listOfNames = names.Split(new char[] { ',' });
// sort the array of strings
Array.Sort(listOfNames);
foreach (string name in listOfNames)
{
ListBox1.Items.Add(name);
}
}
}

The result:
sort an array of strings

In C#, it is extremely easy to sort an array of strings, just use:

Array.Sort(listOfNames);

where listOfNames is an array of strings.

Sep 1

This is the case scenario: if you have a form and in the form you have a button, if you press the button can you actually see a User Control displayed?. A friend of mine asked me this question because in his form he was trying to display a user control doing this:

private void button1_Click(object sender, EventArgs e)
{
UserControl1 userControl = new UserControl1();
userControl.Show();
}

This will not do the trick. What you need to do is to create a form, add the user control to the form, and then display the form. This is a simple way of doing this:

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Show(Control control)
{
Form form = new Form();
form.Controls.Add(control);
form.Show();
}
private void button1_Click(object sender, EventArgs e)
{
UserControl1 userControl = new UserControl1();
Form1 form = new Form1();
form.Show(userControl);
}
}

At this point you will be able to see your user control displayed inside a form.

Jul 28

I have a dataGridView with two columns and multiple rows.

The task: When I pressed the enter key, in any of my dataGridViewCell I want to handle the fact that the user pressed the enter key. I will also get the value they typed.

In order to do this I was trying to simulate an event that Processes the ENTER key. I read about a DataGridView.ProcessEnterKey Method but this didn’t work quite well for me, considering I need to know the index of the current column of my dataGridViewCell.

So how can you simulate this?. First of all the first event that is going to be called is CellEnter. This is the code I have when the user enters the cell

private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
// store the index of the column
columnIndex = e.ColumnIndex;
dataGridView1.BeginEdit(false);
}

Then the next event that is going to be called is EditingControlShowing. This occurs when a control for editing a cell is showing. This is the code I have for this event:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
DataGridViewTextBoxEditingControl dText = (DataGridViewTextBoxEditingControl)e.Control;
dText.KeyUp -= new KeyEventHandler(dText_KeyUp);
dText.KeyUp += new KeyEventHandler(dText_KeyUp);
}

I create a DataGridViewTextBoxEditingControl (according to MSDN: “represents a text box control that can be hosted in a DataGridViewTextBoxCell” ) of the current cell, and remove and add to that control a KeyUp event, which is the next event that gets called.

The KeyUp event according to MSDN: “occurs when a key is released while the control has focus.”. The code for the KeyUp events looks like this:

void dText_KeyUp(object sender, KeyEventArgs e)
{
int rowIndex = ((System.Windows.Forms.DataGridViewTextBoxEditingControl)(sender)).
EditingControlRowIndex;
if (e.KeyCode == Keys.Enter)
{
object valueEntered = dataGridView1[columnIndex, rowIndex - 1].EditedFormattedValue;
MessageBox.Show("The Enter Key was detected. The value entered was: " + valueEntered.ToString());
}
}

At this point you can do something with the fact that the user pressed enter. I am displaying a Message Box with the value entered by the user.

If you know of another way, or a better way to do this , I’ll be very interested to know. At least this is the only way I found to solve this problem.

Here’s a copy of my files.

Jul 28

I had a dataGridView in which if I clicked a cell, it will look like this

before cell enter

I had to click the cell twice to get the focus.I wanted to click the dataGridViewCell and immediately get the focus. Something like this:

after cell enter

Clicking twice the dataGridViewCell to get the focus is annoying. This is the code that helped me to put the focus in the dataGridViewCell immediately:

private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
// puts the current cell in edit mode
dataGridView1.BeginEdit(false);
}

I would also like to thank Lisurc for his input in this topic. He had another solution to it, and it works just as good what is stated above. Thanks for your contribution Lisurc.

If you have another way to solve this problem, please comment it, and let me know.


private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
}

Jul 4

I was trying to add a value to a specific DataGridViewCell. To accomplish these you need to do something like this:

DataGridViewCell cellLotsOfAmount = monitorDataGrid[e.ColumnIndex, e.RowIndex];
cellLotsOfAmount.Value = lotsOfAmount;

This should do the work; however, there may be the case ( as it was happening to me ) that you are doing this inside a method, and for some reason, the value is not being displayed in the DataGridViewCell. I tried lots of things inside this method, that didn’t quite work for me.
If you search around different users will probably suggest to
- Invalidate the cell: monitorDataGrid.InvalidateCell(cell);
- Refresh edit the datagridview: monitorDataGrid.RefreshEdit();
etc,etc,etc

However, what actually worked for me, was to change the value of the cell inside the DataGridView.CellFormatting event. According to the MSDN library this occurs “when the contents of a cell need to be formatted for display.”

My code inside this event looks something like this:

private void monitorDataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// search for the column you are looking for
if (monitorDataGrid.Columns[e.ColumnIndex].HeaderText == "Lots of amount")
{
// get the cell you are looking for
DataGridViewCell cellLotsOfAmount = monitorDataGrid[e.ColumnIndex, e.RowIndex];
// change the value
cellLotsOfAmount.Value = lotsOfAmount;
}
}

Doing this I didn’t have invalidate or refresh the datagridview in order for my value to be displayed. This is how I solved this problem, if this helped you to solve it, or you have a different thought on this, I’ll be glad to know about it.

Jun 20

I actually do this a lot, here’s how:

foreach (DataGridViewRow gridrow in DataGridView.Rows)
{
DataRow datarow = (gridrow.DataBoundItem as DataRowView).Row;
// do something with the datarow
}

Jun 6

Lately, I have been putting my programming practices to the test with FxCop. FxCop makes sure your code conforms the best .NET coding practices.

I will write in a separate post how to use FxCop, but for the moment i will write about some of the improvements FxCop suggested for my code.

Warning, Certainty 95, for UseLiteralsWhereAppropriate
{
Resolution : “Field ‘MOST_ACTIVE’ is declared as ’static readonly’
but is initialized with a constant value ‘Most Active’.
Mark this field as ‘const’ instead.”
}

The line that was causing this warning:
private static readonly string MOST_ACTIVE = “Most Active”;
Solution:
private const string MOST_ACTIVE = “Most Active”;

Warning, Certainty 95, for TestForEmptyStringsUsingStringLength
{
Resolution : “Replace the call to String.op_Inequality(String.Empty)
in ‘MyDefaultPage.Populate(String, String):Void’ with
a call to String.IsNullOrEmpty.”
}

The line that was causing this warning:
if (panel != String.Empty)
Solution:
if (!String.IsNullOrEmpty(panel))

Warning, Certainty 90, for DoNotInitializeUnnecessarily
{
Resolution : “MyDefaultPage.MyDefaultPage() initializes field
behavior of type DeltaOptions.Windows.Forms.Behaviour.IReportFormBehavior
to null. Remove this initialization as it will be done
automatically by the runtime.”
}

The line that was causing this warning:
private IReportFormBehavior behavior = null;
Solution:
private IReportFormBehavior behavior;

Warning, Certainty 95, for RemoveUnusedLocals
{
Resolution : “MyDefaultPage.Populate():Void declares a local,
‘mypageOptions’, of type System.String, which is never
used or is only assigned to. Use this local or remove
it.”
}

The line that was causing this warning:
Some variable that wasn’t being used in a method
Solution:
Delete or comment the variable not used.

These are some of the multiple warnings that FxCop can point about your code. As you noticed, running your code against this tool will improve your source code greatly.

Jun 5

Today I’ve been wondering how to set a DataGridViewComboBoxColumn to a default value. The reason I wanted do this, is because i want the combo box to have a default value when the datagridview is loaded in the screen.

The line to accomplish this is the following:

DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.DefaultCellStyle.NullValue = "Buy";

« Previous Entries