views:

226

answers:

2

Hi,

I am working on a form with datagridview and webbrowser controls. I have three columns as URL, username and password in datagridview. What I want to do is to automate the login for some websites that I use frequently. For that reason I am not sure if this is the right approach but I created the below code. The problem is with the argument of switch.

I will click the row on datagridview and then click the login_button so that the username and password info will be passed to the related fields on the webpage. Why I need a switch-case loop is because all the webpages have different element IDs for username and password fields.

As I said, I am not sure if datagridview allows switch-case, I searched the net but couldn't find any samples.

private void login_button_Click(object sender, EventArgs e)
    {
        switch (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString())
        {
            case "http://www.website1.com":
                webBrowser1.Document.GetElementById("username").InnerText = dataGridView1.Rows[3].Cells[3].Value.ToString();
                webBrowser1.Document.GetElementById("password").InnerText = dataGridView1.Rows[3].Cells[4].Value.ToString();
                return;
            case "http://www.website2.com":
                webBrowser1.Document.GetElementById("uname").InnerText = dataGridView1.Rows[4].Cells[3].Value.ToString();
                webBrowser1.Document.GetElementById("pswd").InnerText = dataGridView1.Rows[4].Cells[4].Value.ToString();
                return;
        }
        HtmlElementCollection elements = this.webBrowser1.Document.GetElementsByTagName("Form");
        foreach (HtmlElement currentElement in elements)
        {
            currentElement.InvokeMember("Login");
        }
    }
A: 

Have you made sure that

dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();

returns the URL?

That would be the first place to start.

Maybe:

dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString()

As for the datagrid + switch, the datagrid doesn't know/care about the switch. All it knows that when the button is pressed call:

private void login_button_Click(object sender, EventArgs e)

What happens if you hardcode the URL? Does everything else work?

EDIT: D'oh that isn't going to work! You have returns in your switch. So you are ending the method and never calling:

  HtmlElementCollection elements = this.webBrowser1.Document.GetElementsByTagName("Form");
    foreach (HtmlElement currentElement in elements)
    {
        currentElement.InvokeMember("Login");
    }
NitroxDM
A: 

I'm not sure if it's definite like this in C#, but you may have to perform the switch on a temporary variable e.g.

string site = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
switch(site)
{
....
}

if nothing else it will make debugging easier.

also each case should end with a break; not a return;

geocoin