execute code when select is clicked in GridView - asp.net

I have a GridView and a select link in the GrdiView, when the item is selected I want it to read the contents to a textbox below the GridView. The only way I can think is by accessing the behind code for the onClick function of the select link. The problem is I am unsure how to do this.
UPDATED jams method:
C# code
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
GridView1.SelectedIndex = e.NewSelectedIndex;
TextBox1.Text = GridView1.Rows[e.NewSelectedIndex].Cells[0].Text;
}
front code
<asp:GridView ID="GridView1" OnSelectedIndexChanging="GridView1_SelectedIndexChanging" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333"
GridLines="None">
UPDATE my method:
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
int i = GridView1.SelectedIndex;
ds.Tables["Comments"].Rows[i]["Comment"] = TextBox1.Text;
}
also tried this but I get an error -> System.IndexOutOfRangeException: There is no row at position -1.
Thanks.

You need to attach OnSelectedIndexChanged event with your gridview
<asp:GridView OnSelectedIndexChanged="GridView1_SelectedIndexChanged" />
Then in code behind you could do:
void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
{
GridViewRow row = CustomersGridView.SelectedRow;// you will get the selected row
someLabel.Text = row.Cells[0].Text;
}

Once you attach to the selectedindexchanged event you need to also set up some datakeys so you can retrieve values from your grid. See sample here.
void CustomersGridView_SelectedIndexChanged(Object sender, EventArgs e)
{
// Determine the index of the selected row.
int index = CustomersGridView.SelectedIndex;
// Display the primary key value of the selected row.
Message.Text = "The primary key value of the selected row is " +
CustomersGridView.DataKeys[index].Value.ToString() + ".";
}

it is better to use oORowCommand event of the grid view and pass the command argument and commandName to the same event as a attribute value. Then i think it will work.

Related

can't get values from items on dropdownlist

I have this in my page:
<asp:DropDownList ID="membros" runat="server">
</asp:DropDownList>
and in the code behind, I have this:
protected void Page_Load(object sender, EventArgs e)
{
members.Items.Clear();
members.Items.Add(new ListItem("Choose...", ""));
foreach (DataRow item in com.Execute("select * from tableMembers").Rows)
{
members.Items.Add(new ListItem(item["name"].ToString(), item["id_user"].ToString()));
contForeach++;
}
}
and when I try to get the value from SelectedIndex I can't because he always get me 0 independently of what index I choose.
put that in if(!IsPostBack) so that it can load the dropdown at first time the form loads,right now it is loading everytime the page loads so your missing your selection.
if(!IsPostBack)
{
members.Items.Clear();
members.Items.Add(new ListItem("Choose...", ""));
foreach (DataRow item in com.Execute("select * from tableMembers").Rows)
{
members.Items.Add(new ListItem(item["name"].ToString(), item["id_user"].ToString()));
contForeach++;
}
}
Apart from the IsPostBack mentioned, you should be doing it this way instead of looping through the data
Modify your markup
<asp:DropDownList ID="membros" runat="server" DataTextField="name" DataValueField="user_id">
From code behind, bind the data
if(!IsPostBack)
{
DataTable dt = com.Execute("select * from tableMembers");
members.DataSource = dt;
members.DataBind();
members.Items.Insert(0, new ListItem("Choose...", ""));
}
Bound controls like DropdownList, GridView, DataList etc have DataSource property that you can use to assign a collection to them and they would loop through it and extract the data.

CheckBox handling oncheck changed in ASP.net

i had a DataList view which i add a check box in the Item Template
i want each item i select to increase some counter for examble once it's checked ..
i used the following code to handle that ,but the event function is never accessed ?!
protected void selectItemCheckBox_CheckedChanged(object sender, EventArgs e)
{
int selected = 0;
foreach (DataListItem i in DataList1.Items)
{
CheckBox chk = (CheckBox)i.FindControl("selectItemCheckBox");
if (chk.Checked)
{
selected++;
}
selectedItemCount.Text = Convert.ToString(selected);
}`
}
Currently you're looping over every checkbox for every checked checkbox which is inefficient and depending on your other code, may be causing trouble.
You're better off incrementing for each checkbox individually.
...DataList...
<ItemTemplate>
<asp:CheckBox id="selectItemCheckBox" runat="server"
AutoPostBack="True"
OnCheckedChanged="selectItemCheckBox_CheckedChanged" />
</ItemTemplate>
...DataList...
After a box is checked, update the total for just that checkbox using sender
protected void selectItemCheckBox_CheckedChanged(object sender, EventArgs e)
{
// Parse the total selected items from the TextBox.
// You may consider using a Label instead, or something non-editable like a hidden field
int totalChecked;
if (int.TryParse(selectedItemCount.Text, out totalChecked) = false)
totalChecked = 0;
// Get a reference to the CheckBox
CheckBox selectItemCheckBox = (CheckBox)sender;
// Increment the total
if (selectItemCheckBox.Checked == true)
totalChecked++;
// Put back in the TextBox
selectedItemCount.Text = totalChecked.ToString();
}

How to access Repeater FooterTemplate TextBox?

What I am trying to do is to access the value from the TextBox1 to display back on the screen.
I tried to access it from the Page_Load() and the OnItemDataBound and they both failed.
It seem like the code is able to access the control but it return nothing back.
protected void Page_Load(object sender, EventArgs e)
{
Literal Literal1 = (Literal)Repeater1.Controls[Repeater1.Controls.Count - 1].FindControl("Literal1");
Response.Write(Literal1.Text);
//this techique is not working for the line below
TextBox TextBox1 = (TextBox)Repeater1.Controls[Repeater1.Controls.Count - 1].FindControl("TextBox1");
Response.Write(TextBox1.Text);
}
public void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
//this techique is not working
if (e.Item.ItemType == ListItemType.Footer)
{
TextBox TextBox1 = (TextBox)e.Item.FindControl("TextBox1");
Response.Write(TextBox1.Text);
}
}
I'm not sure what you mean by "they both failed" but if the Text property of the Textbox is empty i might be because you are rebinding your repeater on each post back. Try wrapping your repeater .DataBind() with a !IsPostBack condition.
I have to use "Literal" as an alternate solution by passing the html Textbox problem. I do not like this solution but i guess i have to use it.

How to get selected row of detail grid in Master-Detail GridView?

I'm having a problem on getting the selected rows values of a detail grid. I have master-detail grid in a popup control and it works fine. I also enabled the enable selection to have checkboxes but when i try to run GetSelectedFieldValues on ClientSideEvents of a button it always returns "0". What do i do wrong, i couldn't find it?
Here is the detail grid:
AutoGenerateColumns="False"
CssFilePath="~/App_Themes/Aqua/{0}/styles.css"
CssPostfix="Aqua"
OnBeforePerformDataSelect="gv_ParameterTempD_BeforePerformDataSelect"
ClientInstanceName="gvC_ParameterTempD">
<dxwgv:GridViewCommandColumn
ShowSelectCheckbox="True"
VisibleIndex="0">
</dxwgv:GridViewCommandColumn>
<dxwgv:GridViewDataTextColumn
Caption="Detay Kodu"
FieldName="PrmDetailCode"
VisibleIndex="0">
</dxwgv:GridViewDataTextColumn>
<dxwgv:GridViewDataTextColumn
Caption="Seçim Adı"
FieldName="PrmDetailName"
VisibleIndex="2">
</dxwgv:GridViewDataTextColumn>
<dxwgv:GridViewDataTextColumn
Caption="Seçim Adı(Grup)"
FieldName="PrmDetailNameG"
VisibleIndex="3">
</dxwgv:GridViewDataTextColumn>
<dxwgv:GridViewDataTextColumn
Caption="Seçim Adı(Stok)"
FieldName="PrmDetailNameS"
VisibleIndex="4">
</dxwgv:GridViewDataTextColumn>
<dxwgv:GridViewDataTextColumn
Caption="Grup Seçimi Yapan"
FieldName="PrmGroupSelector"
VisibleIndex="5">
</dxwgv:GridViewDataTextColumn>
<dxwgv:GridViewDataTextColumn
Caption="Stok Seçimi Yapan"
FieldName="PrmStokSelector"
VisibleIndex="6">
</dxwgv:GridViewDataTextColumn>
</Columns>
And this is the button:
<ClientSideEvents Click="function(s,e)
{
pcc_Question.Hide();
gvC_ParameterTempD.GetSelectedFieldValues('PrmDetailName;PrmDetailNameG;PrmDetailNameS',ShowCellValue);
}"
/>
</dxe:ASPxButton>
and this is the jsscript:
function ShowCellValue(values) {
var value = condition.GetText();
alert(values.length); // here it returns "0"
if(value != "")
{
var newValue = ' ' + value + values + ' = ';
condition.SetText(newValue);
}
else
{
for(var i = 0; i < values.length; i ++) {
value += values[i];
}
condition.SetText(value);
}
}
I don't know what i do wrong,
Thanks for the help
Am I right in my assumption that the button is residing in the same DetailRowTemplate container? Anyway, it is necessary to access the proper instance of the detail GridView object. To do this, set the grid's ClientInstanceName property to a dynamic value. This should allow you to access the proper grid instance and fetch selected row values. A sample code is available at:
http://www.devexpress.com/Support/Center/ViewIssue.aspx?issueid=Q90007
I'm setting the DataSource at Runtime but i do not call DataBind method, because it makes BeforePerformDataSelect of the Detail Grid to perform more than one.
This code set the master grids datasource and bind it:
protected void
gv_Answers_CustomCallback(object
sender,
ASPxGridViewCustomCallbackEventArgs e)
{
ConfPrmMTempCollection _ConfPrmMTempCollection = new ConfPrmMTempCollection();
masterKey = e.Parameters;
if (masterKey != "")
{
man.Add(new SqlOperatorEquality("MAND_CONF_PRM_M_TEMP.PARAMETER_M_TEMP_ID", Convert.ToInt32(masterKey)));
gv_Answers.DataSource = gc.LoadCollectionFromCollType(typeof(ConfPrmMTempCollection),man);
gv_Answers.DataBind();
man.Clear();
}
}
And this code is for setting the datasource of the detail grid:
protected void
gv_ParameterTempD_BeforePerformDataSelect(object
sender, EventArgs e)
{
ASPxGridView detailGrid = sender as ASPxGridView;
masterKey = detailGrid.GetMasterRowKeyValue().ToString();
man.Add(new SqlOperatorEquality("MAND_CONF_PRM_D_TEMP.PARAMETER_M_TEMP_ID", Convert.ToInt32(masterKey)));
detailGrid.DataSource = gc.LoadCollectionFromCollType(typeof(ConfPrmDTempCollection),man);
}
I see that you set the master grid's DataSource in the CustomCallback event handler. Try to cache the masterKey value in a Session variable and set the grid's DataSource not only in the CustomCallback event handler but also in the Page_Init method:
protected void Page_Init(object sender, EventArgs e) {
if(Session["masterKey"] == null)
return;
ConfPrmMTempCollection _ConfPrmMTempCollection = new ConfPrmMTempCollection();
masterKey = Session["masterKey"].ToString();
if (masterKey != "")
{
man.Add(new SqlOperatorEquality("MAND_CONF_PRM_M_TEMP.PARAMETER_M_TEMP_ID", Convert.ToInt32(masterKey)));
gv_Answers.DataSource = gc.LoadCollectionFromCollType(typeof(ConfPrmMTempCollection),man);
man.Clear();
}
}
protected void Page_Load(object sender, EventArgs e) {
gv_Answers.DataBind();
}
Does this help?
I have created a sample project based on your description and it works fine. It is available to download from:
http://www.devexpress.com/Support/Center/ViewIssue.aspx?issueid=Q220495

set tool tip for each cell of a devexpress gridview

how to set tool tip for each cell of a devexpress gridview in asp.net & c#.net
First, set the "OnHtmlDataCellPrepared" property of your grid, like this:
<dx:ASPxGridView ID="ASPxGridView1" runat="server"
OnHtmlDataCellPrepared="ASPxGridView1_HtmlDataCellPrepared">
</dx:ASPxGridView>
Then set the "title" attribute of the cells in your codebehind:
protected void ASPxGridView1_HtmlDataCellPrepared(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewTableDataCellEventArgs e)
{
e.Cell.Attributes.Add("title", "Your Tooltip");
}
Same concept as mhughes but in my case the gridView is dynamically created so I had to add the event handler after the fact.
_gridview.HtmlDataCellPrepared += new ASPxGridViewTableDataCellEventHandler(_gridview_HtmlDataCellPrepared);
void _gridview_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e)
{
if (e.CellValue != null)
e.Cell.Attributes.Add("title", e.CellValue.ToString());
}

Resources