Saturday, March 24, 2012

Populate insert form field from GridView selection

Hi,

I'm trying to do something that seems like it should be simple, but I'm having trouble getting it to work. I have a page with a GridView and a FormView in Insert mode.

When the user selects a row in the gridview, I want to take the data keys from that selection and populate them to the appropriate textboxes in the form. I'm trying to do this in the

"GridView1_SelectedIndexChanged event" with the following code:

TextBox t;

t = (TextBox)FormView1.FindControl("myTextBox");

t.Text = (String)GridView1.SelectedDataKey.Values[0];

The text in "myTextBox" doesn't change, it remains blank. I've tried to find another event in which to put this code but so far no luck. I'm a newbie so I'm sure it's something obvious.

Can anyone help me with this? Thanks in advance.

Try moving your code to the FormView.DataBound event.


Hi Ed,

When I do that, I get "Object reference not set to an instance of an object. " I'm guessing that this is because the formview1_databound fires when the page is first loading, before there is a selected key from the gridview. I'm not sure that this is the case, it's just my best guess.

Do you have any suggestion for a workaround or alternate approach?

Thanks.


Once try this

ProtectedSub GridView1_SelectedIndexChanged(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles GridView1.SelectedIndexChanged

Formview1.PageIndex = GridView1.SelectedIndex

EndSub


Hi Mahesh,

Okay, now I have this code but I still don't see the text I want populated into the text box. What am I doing wrong?

protectedvoid GridView1_SelectedIndexChanged(object sender,EventArgs e)

{

FormView1.PageIndex = GridView1.SelectedIndex;

TextBox t;

t = (TextBox)FormView1.FindControl("myTextBox");

t.Text = (String)GridView1.SelectedDataKey.Values[0];

}


How about this:


protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{

for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (GridView1.SelectedIndex == i)
{
TextBox t;

t = (TextBox)FormView1.FindControl("myTextBox");
t.Text = (String)GridView1.SelectedDataKey.Values[0];
}
}
}


Within your FormView.DataBound event, simply place a conditional statement which checks for the existence of a SelectedItem.

if (!GridView1.SelectedIndex.Equals(-1))


That did it! Thanks very much (I told you that I was a newbie :-).

0 comments:

Post a Comment