I have gridview with template field of dropdownlist in each row.when i select any value from dropdownlist it will change color of 3rd row below than it.But when i click on another dropdownlist it is changing the color of 3rd row below than it but the index of previous dropdownlist is not changed to 0 i.e"Select".it is still showing the value selected in last dropdown list.I just want when i click on a dropdownlist ,all other dropdownlist should be indexed to 0 i.e "Select" except one which i have clicked.
I am doing following in Selectedindexchange event of dropdownlist:
protected void GridView1_SelectedIndexChanged(object sender,EventArgs e)
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
int g1 = gvRow.RowIndex;
GridView1.Rows[g1].BackColor = Color.White;
}
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.NamingContainer;
int g = row.RowIndex + 3;
int current_row_index = row.RowIndex;
int pp = GridView1.Rows.Count;
GridView1.Rows[g].BackColor = Color.Red;
}
}
Thanks in advance.
Just use DropdownName.ClearSelection() for each of your other dropdown except the one where you are calling Selectedindexchange event.
Maybe something like this:
protected void GridView1_SelectedIndexChanged(object sender,EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.NamingContainer;
int g = row.RowIndex + 3;
int current_row_index = row.RowIndex;
foreach (GridViewRow gvRow in GridView1.Rows)
{
gvRow.BackColor = Color.White;
if (gvRow.FindControl("nameOfTheDropdown") != null && gvRow.RowIndex != current_row_index)
{
((DropDownList)gvRow.FindControl("nameOfTheDropdown")).SelectedIndex = 0;
}
}
GridView1.Rows[g].BackColor = Color.Red;
}
Regards
Related
I have a gridview with first columns is same as headers i.e. same value with autogeneratecolumns as true, what i need to do in RowDatabound if HeaderText Equals to Intersect of the first Column text, Change the color to Yellow. Please see the attached image of the Desireed Gridview Output.
GridViewDesiredOutput
HTML
<asp:GridView ID="GvSamples" OnRowDataBound="GvSamples_RowDataBound" runat="server" AutoGenerateColumns="True">
C#
public void BindSamplesGrid()
{
DataTable _dt = new DataTable();
_dt = BL.GetSample(_conn);
GvSamples.DataSource = _dt;
GvSamples.DataBind();
}
protected void GvSamples_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
if (e.Row.Cells[i].Text == e.Row.Cells[i].Text)
e.Row.Cells[i].Text = e.Row.Cells[i].Text.Replace("_", " ");
}
}
}
I am using asp.net C# Gridview.
Thank you
There are a couple of issues with your code. First of all you can only access the header row in DataControlRowType.Header, so coloring the cells as desired must be done in DataControlRowType.DataRow.
Next you are evaluating exactly the same value, so it will always be true: e.Row.Cells[i].Text == e.Row.Cells[i].Text, although this does not seem to do much except replace a _, which has nothing to do with getting the cell color to be yellow.
The below snippet does what you need. It gets the current row number and colors the correct cell yellow.
protected void GvSamples_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//get the current row number
int rowIndex = e.Row.RowIndex;
//check if the rownumber does not exceed the column count
if (rowIndex < e.Row.Cells.Count - 1)
{
//make the cell yellow
e.Row.Cells[rowIndex + 1].BackColor = Color.Yellow;
}
}
}
In my asp.net application, I have used Gridview control, In which i have to add Dropdownlist at runtime for each cell.Which i am able to bind successfully.
Below is my code which inside row databound event,
foreach (GridViewRow row in gdvLocation.Rows) {
if (row.RowType == DataControlRowType.DataRow) {
for (int i = 1; i < row.Cells.Count; i++) {
var dlRouteType = new DropDownList();
dlRouteType.ID = "ddlRouteType";
dlRouteType.DataSource = GetRouteTypeList();
dlRouteType.DataTextField = "RouteType";
dlRouteType.DataValueField = "Id";
dlRouteType.DataBind();
row.Cells[i].Controls.Add(dlRouteType);
}
}
}
I have a button in my page, which has functionality to save data to database . While saving data i have to pass the value from Dropdownlist which i have added at runtime. On button click i am writing following code to get data from dropdownlist,
var ddlDropDown = (DropDownList)row.Cells[i].FindControl("ddlRouteType");
But i am getting null in ddlDropDown object. I have even added Update panel inside aspx page. Any suggessions most welcome.
Thanks in advance
Sangeetha
You have these errors in your code
RowDataBound already iterates through each rows and so all you need not write that foreach on top
You are iterating from index 1, index are zero-based. So start from zero.
The DropDownList ID must be unique, so better write something like,dlRouteType.ID = "ddlRouteType_" + i;
The code should be,
protected void gdvLocation_RowDataBound(object sender, GridViewRowEventArgs e)
{
//removed the foreach loop
var row = e.Row;
if (row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < row.Cells.Count; i++) //changed index
{
var dlRouteType = new DropDownList();
dlRouteType.ID = "ddlRouteType_" + i; //gave unique id
dlRouteType.DataSource = GetRouteTypeList();
dlRouteType.DataTextField = "RouteType";
dlRouteType.DataValueField = "Id";
dlRouteType.DataBind();
row.Cells[i].Controls.Add(dlRouteType);
}
}
}
I am having some problem for getting the text from textbox in a row which the checkbox was marked check in gridview. When button on click, it supposed to get the checked row index for prodID and the quantity which is the text from textbox:
protected void lbnConfirm_Click(object sender, EventArgs e)
{
string quantity = "" , prodID = "";
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Panel pnl = item.FindControl("pBody1") as Panel;
GridView gv = pnl.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
//Get the productID which set as DataKeyNames for selected row index
prodID = gv.DataKeys[gr.RowIndex].Value.ToString();
var tbQuantity = gr.FindControl("tbQuantity") as TextBox;
if (tbQuantity != null)
{
quantity = tbQuantity.Text;
}
tempList.Add(prodID);
}
}
}
}
for (int i = 0; i < tempList.Count; i++)
{
//Testing
lblTest.Text += tempList[i] + " " + quantity;
}
}
Let's say I got prodID 1 with 50 units, prodID 2 with 77 units, prodID 3 with 90 units. When I loop thru the tempList, this is the result which I supposed to get:
1 50units, 2 77units, 390units
However, the codes does not get the quantity from the textbox for each product independently. Here is the result which I get:
1 90units, 2 90units, 3 90units
It just simply get the quantity of last product in the list. I wonder is there any way to fix this? Thanks in advance.
Edited Portion:
foreach (string key in tempList.Keys)
{
packagesNeeded = 1;
unitQty = prodPackBLL.getUnitQtySPU(tempList[key]);
lblTest.Text += key + " " + tempList[key];
if (Convert.ToInt32(quantity) < (packagesNeeded * unitQty))
{
//Pop up message
Page.ClientScript.RegisterStartupScript(GetType(), "UserDialogScript", "alert(\"Insufficient storage\");", true);
}
}
You can use Dictionary to pair each prodID with its corresponding quantity. Try this code:
protected void lbnConfirm_Click(object sender, EventArgs e)
{
Dictionary<string, string> tempList = new Dictionary<string, string>();
string quantity = "", prodID = "";
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Panel pnl = item.FindControl("pBody1") as Panel;
GridView gv = pnl.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
//Get the productID which set as DataKeyNames for selected row index
prodID = gv.DataKeys[gr.RowIndex].Value.ToString();
var tbQuantity = gr.FindControl("tbQuantity") as TextBox;
if (tbQuantity != null)
{
quantity = tbQuantity.Text;
}
tempList.Add(prodID, quantity);
}
}
}
}
foreach (string key in tempList.Keys)
{
packagesNeeded = 1;
unitQty = prodPackBLL.getUnitQtySPU(key);
lblTest.Text += key + " " + tempList[key];
if (Convert.ToInt32(tempList[key]) < (packagesNeeded * unitQty))
{
//Pop up message
Page.ClientScript.RegisterStartupScript(GetType(), "UserDialogScript", "alert(\"Insufficient storage\");", true);
}
}
}
Based on your examples above, tempList["1"] will produce "50", tempList["2"] will produce "77", and tempList["3"] will produce "90".
It is because you keep overriding variable "quantity" for each row you have the checkbox selected. If you want to store multiple values you need to use List<string> to store the quantities for each row where the checkbox is selected.
Something like below. Note: I haven't tested the code.
protected void lbnConfirm_Click(object sender, EventArgs e)
{
List<string> quantity = new List<string>();
prodID = "";
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Panel pnl = item.FindControl("pBody1") as Panel;
GridView gv = pnl.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
//Get the productID which set as DataKeyNames for selected row index
prodID = gv.DataKeys[gr.RowIndex].Value.ToString();
var tbQuantity = gr.FindControl("tbQuantity") as TextBox;
if (tbQuantity != null)
{
quantity.Add(tbQuantity.Text);
}
tempList.Add(prodID);
}
}
}
}
for (int i = 0; i < tempList.Count; i++)
{
//Testing
lblTest.Text += tempList[i] + " " + quantity[i];
}
}
you can do something like :
foreach (DataGridViewRow item in GV.Rows)
{
if (Convert.ToBoolean(item.Cells[0].Value) == true)
//here you get the rowcell value :
string val = item.Cells[1].Value.ToString();
//If you want to convert to a textbox :
TextBox textBox = (TextBox)item.Cells[1].Value;
}
where GV is the gridview Id
and checkbox is the 0 column and the value you might want to get is the 1 column
my gridview Row command code looks like
protected void GridView_Admins_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView sourceGrid = sender as GridView;
int currentIndex = 0;
GridViewRow currentRow = null;
if (string.Compare(e.CommandName, "SHOW", true) == 0)
{
if (int.TryParse(e.CommandArgument.ToString(), out currentIndex))
{
currentRow = sourceGrid.Rows[currentIndex];
if (long.TryParse(sourceGrid.DataKeys[currentRow.RowIndex].Values["EmployeeID"].ToString(), out this.employeeId))
this.ShowAdministrativeRightsForUser();
}
}
}
I also have paging enabled in gridview. When I want to edit record I click on particular cell and i can edit records. However when I am on second page when i click on a cell to edit record, I get error at row currentRow = sourceGrid.Rows[currentIndex]; saying Index out of range.
What can be wrong?
Use this to get the index :
int index = Convert.ToInt32(e.CommandArgument);
After posting this: Custom Header in GridView
...I have a related problem. I have added the table row during OnDataBound, and it shows up, the links are clickable. There are two problems with adding it here: first, if a postback occurs that doesn't DataBind, the row disappears; second, no events are happening when the LinkButtons are clicked. Here is the OnDataBound code:
protected override void OnDataBound(EventArgs e)
{
base.OnDataBound(e);
// Hook up the handler to create the Selection header/footer
// TODO: Wrap this in a function sometime
Table table = (Table)Controls[0];
GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
// TODO: should add css classes
TableHeaderCell cell = new TableHeaderCell();
cell.ColumnSpan = Columns.Count + 1; // plus 1 for the checkbox column
cell.HorizontalAlign = HorizontalAlign.Left; // do this or css?
HtmlGenericControl label = new HtmlGenericControl("label");
label.InnerText = "Select:";
selectNoneLK = new LinkButton();
selectNoneLK.ID = "SelectNoneLK";
selectNoneLK.Text = "None";
selectNoneLK.Click += SelectNoneLK_Click;
//selectNoneLK.CommandName = "SelectNone";
//selectNoneLK.Command += SelectNoneLK_Click;
selectAllLK = new LinkButton();
selectAllLK.ID = "SelectAllLK";
selectAllLK.Text = "All on this page";
//selectAllLK.CommandName = "SelectAll";
//selectAllLK.Command += SelectAllLK_Click;
selectAllLK.Click += SelectAllLK_Click;
cell.Controls.Add(label);
cell.Controls.Add(selectNoneLK);
cell.Controls.Add(selectAllLK);
row.Controls.Add(cell);
// Find out where to put this row
int rowIndex = 0;
if(SelectionMode == SelectionMode.AboveHeader)
{
rowIndex = 0;
}
else if(SelectionMode == SelectionMode.BelowHeader)
{
rowIndex = 1;
}
else if(SelectionMode == SelectionMode.AboveFooter)
{
rowIndex = table.Rows.Count;
}
else if(SelectionMode == SelectionMode.BelowFooter)
{
rowIndex = table.Rows.Count + 1;
}
table.Rows.AddAt(rowIndex, row);
}
You can try putting it in the RowCreated Event, while the header is being created. This might also fix your problem with the LinkButtons not working.
void GridView1_RowCreated(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.Header)
{
...your code here
}