AspxGridView selection at runtime - c#

I have an aspxGridView on my page, and i create the columns at runtime. I also add CommandColumn with ShowSelectCheckBox set to true. But after i select one row and click a button to get the row values, AspxGridView.Selection.Count returns 0. I create this GridView on AspxButtons Click event also for paging, create the gridView on Page_Init. Here is the code to create the AspxGridView:
Colenter code hereorCollection colorCol = ConfAttributesManager.Instance
.GetColors();
if (colorCol.Count > 0)
{
GridViewDataTextColumn grdColorCodeColumn = new GridViewDataTextColumn();
grdColorCodeColumn.FieldName = "ColorCode";
GridViewDataTextColumn grdDescriptionColumn = new GridViewDataTextColumn();
grdDescriptionColumn.FieldName = "Description";
gv_Attributes.Columns.Clear();
gv_Attributes.Columns.Add(grdColorCodeColumn);
gv_Attributes.Columns.Add(grdDescriptionColumn);
GridViewCommandColumn grdCmdColumn = new GridViewCommandColumn();
grdCmdColumn.ShowSelectCheckbox = true;
grdCmdColumn.VisibleIndex = 0;
gv_Attributes.Columns.Add(grdCmdColumn);
gv_Attributes.DataSource = colorCol;
gv_Attributes.DataBind();
}
I don't know where do i make a mistake?
Thanks for your help.

It seems that you do not specify the ASPxGridView.KeyFieldName property that is required for Row Selection operation:
gv_Attributes.KeyFieldName = "ColorCode";
//gv_Attributes.KeyFieldName = Unique Key Field;

Related

How to assign value to text box control inside the table column in C# coding file?

I am creating asp.net web form. in that i am creating dynamic tables in which particular column is numeric text box control.
i don't know how to assign and get values from the text box control.. my coding as follow..
for (int i = 0; i < my_DataTable.Rows.Count; i++)
{
HtmlTableRow _Row = new HtmlTableRow();
HtmlTableCell Col = new HtmlTableCell();
Col.InnerText = my_DataTable.Rows[i]["itmCode"].ToString();
_Row.Controls.Add(Col);
Col = new HtmlTableCell();
_Row.Controls.Add(Col);
Col.InnerHtml = "<input type='number' value='0'>";
_Row.Controls.Add(Col);
my_Table.Rows.Add(_Row);
}
In a paricular method, i need to assign the value to the text box control also needs to get the value existing value.. so i try follow as below
var no_1 = my_Table.Rows[0].Cells[1].InnerText;
If i check the no_1, it has the textbox, but i don't know how to access the current value and assign new value..
can anyone help me how to achieve this..
One thing you have to keep in mind while working with Dynamic Controls is that whenever a postback has occurred you will lose the dynamically created controls(as the postback calls the Page_load() event so if you don't have them at the load event they will not be generated and hence will not be displayed.). So, it is always better to re-render the controls in the load event.
So, in order to get the value of the dynamically assigned controls (either HTML or Asp.net) here is how i would do that.
First, create a holder which will be used to store the controls in the page either with runat="server"(So, you can access that control in the backend). In your case, that control is my_Table. Then use the Session/ViewState to keep a track of all the created dynamic controls which can be used re-render the controls with their values as:
To add a new control in the page it would be like this:
var cnt = _findRelated("txtDynamic") + 1; //for all the dynamic text boxes i am using the prefix of txtDynamic just to keep SOC.
var nId = $"txtDynamic-{cnt}";
var _ctrl = new HtmlInputText("Integer")
{
Name = nId,
ID = nId,
//Value="Default Value" //uncomment to assign a default value
};
_ctrl.Attributes.Add("runat", "server");
var row = new System.Web.UI.HtmlControls.HtmlTableRow();
var newCell = new HtmlTableCell();
newCell.Controls.Add(_ctrl);
row.Cells.Add(newCell);
my_Table.Rows.Add(row);
Session.Add(cnt.ToString(), _ctrl); //here i am using session to manage the controls but you can also use the ViewState
In the above code i am using HtmlInputText to generate an <input type="number"></input> with it's constructor taking the type string more can be read at:HtmlInputText.
The _findRelated() method is used to get the number of dynamic text controls appended to the Form. It is defined as:
private int _findRelated(string prefix)
{
string reqstr = Request.Form.ToString();
return ((reqstr.Length - reqstr.Replace(prefix, "").Length) / prefix.Length);
}
To set the value of the dynamically added control we can do something like this(if not assigned at the creation):
var cell = my_Table.Rows[_myTable.Rows.Count-1].cells[0]; //here i have assumed it is in the last row and in the first cell you can change the index to be anything.
var txtDynamic = cell.Controls.OfType<HtmlInputText>().FirstOrDefault();//getting the control
txtDynamic.Value = "<Some thing new>"; //setting the value
Now, to get the assigned the value:
var cell = my_Table.Rows[_myTable.Rows.Count-1].cells[0]; //here i have assumed it is in the last row and in the first cell you can change the index to be anything.
var txtDynamic = cell.Controls.OfType<HtmlInputText>().FirstOrDefault();//getting the control
//now use the .Value property of the control to get the value as:
var nValue = txtDynamic.Value;
And as we know the dynamically added controls will be lost on the postback event then we can create a method which will use the controls stored in the Session and re-render them with their values as:
private void _renderControls()
{
try
{
if (Session.Count > 0)
{
for (int k = 0; k < Session.Count; k++)
{
if (Session[k] != null)
{
var _ctrl = new HtmlInputText("Integer") //you can make it dynamic to add different types of input control
{
Name = ((HtmlInputText)Session[k]).ID,
ID = ((HtmlInputText)Session[k]).ID,
Value = ((HtmlInputText)Session[k]).Value
};
if (_ctrl != null)
{
_ctrl.Attributes.Add("runat", "server");
var row = new System.Web.UI.HtmlControls.HtmlTableRow();
var newCell = new HtmlTableCell();
newCell.Controls.Add(_ctrl);
row.Cells.Add(newCell);
my_Table.Rows.Add(row);
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
Now, let's modify the Page_load() event to call this method on every postback as:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
_renderDynamic(); // this method will be called if there is an postback event to re-render the dynamic controls
}
}
Note:
This is just a sample(there can be a lot better approaches out there).
I have used HtmlInputText with property as Integer to create ainput[type="number"].

how to hide Devexpress xtragrid auto emptybands

In DevExpress XtraGrid an Empty Bands is displayed when one of its column position is set Fixed.
Here is the code:
gridview1.DataSource = ds.Table[0];
gridview1.OptionsView.ColumnAutoWidth = false;
gridview1.PopulateColumns();
GridBand DateGridBand = new GridBand();
DateGridBand.Columns.Add(gridview1.Columns["Date"]);
gridview1.Bands.Add(DateGridBand).Fixed = DevExpress.XtraGrid.Columns.FixedStyle.Left;
GridBand gdBand = new GridBand();
gdBand .Caption = "Details";
gdBand .Columns.Add(gridview1.Columns["No"]);
gdBand .Columns.Add(gridview1.Columns["Qty");
gridview1.Bands.Add(gdBand );
how to avoid the Blank Bands.
Thanks.
You need to remove the header row.
// remove header row
GridView1.OptionsView.ShowColumnHeaders = False;
Knowing the two below will save you some time with further customization.
// remove side indicator
GridView1.OptionsView.ShowIndicator = False;
// remove group header
GridView1.OptionsView.ShowGroupPanel = False;

Can't display linklabel text in a datagridviewlinkcolumn

I have a little but pretty annoying problem:
I have created a datagridview and bound it to a datasource.
Then now I want to add a column which will display links for the user to click.
In order to do that i added a datagridviewlinkcolumn. For each rows of the datagrid I set the value of the cell in that column to the text i want to be displayed. But it shows nothing. All the datagridlinkcolumn is filled with "blank text".
Here is my code:
DataGridViewLinkColumn dgvColDeletion = new DataGridViewLinkColumn();
dgvColDeletion.Name = "Deletion";
dgvColDeletion.HeaderText = "";
dgvColDeletion.ReadOnly = false;
dgvTrainings.Columns.Add(dgvColDeletion);
foreach (DataGridViewRow row in dgvTrainings.Rows)
{
row.Cells["Deletion"].Value = "Delete";
}
dgvColDeletion.Update();
dgvTrainings.Update();
I also tried with setting directly linklabels or datagridviwlinkcells, but the problem still remains.
I cant get any clue why this isn't working.
Any help will be very much appreciated, thanks.
To display the same link text for every cell, set the UseColumnTextForLinkValue property to true and set the Text property to the desired link text.
DataGridViewLinkColumn dgvColDeletion = new DataGridViewLinkColumn();
dgvColDeletion.UseColumnTextForLinkValue = true;
dgvColDeletion.Text = "Delete";
Try this. I hope this will helps to you.
DataGridViewLinkColumn dgvColDeletion = new DataGridViewLinkColumn();
dgvColDeletion.UseColumnTextForLinkValue = true;<br/>
dgvColDeletion.Text = "Delete";<br/>
dgvColDeletion.ActiveLinkColor = Color.White;<br/>
dgvColDeletion.LinkBehavior = LinkBehavior.SystemDefault;<br/>
dgvColDeletion.LinkColor = Color.Blue;<br/>
dgvColDeletion.TrackVisitedState = true;<br/>
dgvColDeletion.VisitedLinkColor = Color.YellowGreen;<br/>
dgvColDeletion.Name = "Delete";<br/>
dgvColDeletion.HeaderText = "Delete";<br/>
if (grid_shared.Columns.Contains("Delete") == false)<br/>
{<br/>
dgvColDeletion.Columns.Add(lnkDelete);<br/>
dgvColDeletion.Columns["Delete"].Width = 40;<br/>
}<br/>
Happy coding..:)

LayoutGrid SetRow and SetColumn not working as intended

I have code that creates a button for each object in a list. When each object is created it is given a name that corresponds to the row and column (i.e. name = row1col2). Each button is generated dynamically, added to the grid and then the row/column are set. At a later time I need to gather the "selected" button data so I can perform actions on the data they represent. When I attempt to get the control data from the buttons everything is fine, except for the grid row/column data. It remains the same for all of the selected rows and columns in a grid.
Creating buttons:
for (int i = 1; i < row.StackCount+1; i++)
{
//create button for the column
stackButton = new Button();
stackButton.Height = ((newRow.Height - 2));
stackButton.Width = ((newRow.Width / row.StackCount) - 2);
stackButton.Background = new SolidColorBrush(Colors.White);
//add the button border
stackButton.BorderBrush = new SolidColorBrush(Colors.Black);
stackButton.BorderThickness = new Thickness(1);
stackButton.Style = Application.Current.Resources["flatButton"] as Style;
//add the button name
stackButton.Name = "Row" + row.LineNumber + "Col" + (i - 1).ToString();
//add the event handler to the button
stackButton.Click += new RoutedEventHandler(stackButton_Click);
//add a new column
newRow.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(newRow.Width, GridUnitType.Star) });
//put the button into the grid
newRow.Children.Add(stackButton);
Grid.SetRow(stackButton, 0);
Grid.SetColumn(stackButton, i-1);
}
Getting the Button data back
g = (Grid)b.Child;
foreach (Button currentButton in g.Children)
{
if (((SolidColorBrush)currentButton.Background).Color == Colors.Gray)
{
//create a stack object
buttonData.StartDate = DateTime.Now;
buttonData.LotNumber = LotDisplay.Text;
buttonData.RoomID = SilverGlobals.CurrentRoom.RoomID;
buttonData.RoomCol = Grid.GetColumn(currentButton);
buttonData.RoomRow = Grid.GetRow(currentButton);
buttonData.TrayCount = int.Parse(currentButton.Content.ToString());
buttonData.Status = 0;
//add stack object to list of stack objects
stacks.Add(buttonData);
}
}
I know this must be something small I am missing. Anyone got any ideas?
Although the comment in your second section of code says:
//create a stack object
you don't actually create a new stack object so it is simply overwriting the single instance of buttonData on each iteration. The values for row and column that you see at the end are the last iteration's values.
The net effect is that stacks is a collection of all the same instance of an object instead of a collection of separate instances.
This is just a shot in the dark, but based on this question and this question, it might be that you need to set the Row and Column properties before you add the button to its parent - something like this:
//put the button into the grid
Grid.SetRow(stackButton, 0);
Grid.SetColumn(stackButton, i-1);
newRow.Children.Add(stackButton);

Events not firing for dynamic columns in SharePoint DataGrid

In a Web Part for Sharepoint, I'm trying to add a variable number/ordering of ButtonColumns to a DataGrid dynamically based on an option the user has selected. The problem is that the dynamic columns aren't firing off the events I set up on the DataGrid (such as SelectedIndexChanged). When the table originally constained a static set of columns, they were created in CreateChildControls() and everything worked peachy. However, since they are now dynamic, I have to delay adding them until after a search button's click event fires. I was wondering if there was some place I needed to move the column creation to that still allowed it to be dynamic but also allowed it to register/fire events.
outputDG creation in CreateChildControls():
outputDG = new System.Web.UI.WebControls.DataGrid();
outputDG.CellPadding = 4;
outputDG.HeaderStyle.Font.Bold = false;
outputDG.HeaderStyle.Font.Name = "Verdana";
outputDG.HeaderStyle.BackColor = Color.FromArgb(242,242,242);
outputDG.HeaderStyle.ForeColor = Color.FromArgb(128,128,128);
outputDG.HeaderStyle.Wrap = false;
//outputDG.ItemStyle.BorderColor = Color.Navy;
outputDG.HorizontalAlign = HorizontalAlign.Left;
//outputDG.BorderWidth = 1;
outputDG.GridLines = GridLines.Horizontal;
outputDG.Width = propsMgr.SearchGridWidth;
outputDG.PageSize = 10;
outputDG.AllowPaging = true;
outputDG.PagerStyle.Mode = PagerMode.NumericPages;
outputDG.PagerStyle.PageButtonCount = 5;
outputDG.PagerStyle.NextPageText = "Next Page";
outputDG.PagerStyle.PrevPageText = "Previous Page";
outputDG.PagerStyle.Visible = true;
outputDG.PageIndexChanged += new DataGridPageChangedEventHandler(this.outputDG_PageIndexChanged);
outputDG.AllowSorting = false;
outputDG.SortCommand += new DataGridSortCommandEventHandler(this.outputDG_SortCommand);
outputDG.SelectedItemStyle.BackColor = Color.FromArgb(255,244,206);
outputDG.SelectedIndexChanged += new EventHandler(this.outputDG_SelectedIndexChanged);
outputDG.ItemCreated += new DataGridItemEventHandler(this.outputDG_ItemCreated);
outputDG.AutoGenerateColumns = false;
outputDG.ItemCommand += new DataGridCommandEventHandler(outputDG_ItemCommand);
Controls.Add(outputDG);
During the search button's click event:
ButtonColumn buttonColumnSelect = new ButtonColumn();
buttonColumnSelect.ButtonType = ButtonColumnType.LinkButton;
buttonColumnSelect.CommandName = "Select";
buttonColumnSelect.HeaderText = "Column";
buttonColumnSelect.DataTextField = "columnField";
outputDG.Columns.Add(buttonColumnSelect);
And then later on it that same event I go through the result set and add in my data rows. Like I mentioned, this all worked back when the ButtomColumn code was up in CreateChildControls(), but it stopped working as soon as it was moved into an event. My best guess is that the event for the column doesn't have a chance to register in order to fire since it's happening from a different event. If I need to tackle this problem by building up the DataGrid differently, I'm definitely willing; I just need to be able to dynamically specify different columns to use.
maybe u need to set the ID-Attribute on the DataGrid.
otherwise it would be difficult for asp to find your control.
The fix for my case was to move the adding of the columns to the page's load event and the adding of the DataGrid to the controls after all of the columns are added.

Categories