In GridView Header Row DropDownList to select header column mapping - c#

I Created a application which will map the data and save the Data fields. For that first row in my GridView I added new HearerRow with dropdownlist.
Below is my code which I have attached.
My HTML Page code:
<asp:GridView ID="gvDataMapping" runat="server" AutoGenerateColumns="false">
</asp:GridView>
And Code Behind:
for (int i = 0; i < dtValues.Columns.Count; i++)
{
BoundField boundfield = new BoundField();
boundfield.DataField = dtValues.Columns[i].ColumnName.ToString();
boundfield.HeaderText = dtValues.Columns[i].ColumnName.ToString();
gvDataMapping.Columns.Add(boundfield);
}
gvDataMapping.DataSource = dtValues;
gvDataMapping.DataBind();
GridViewRow HeaderGridRow = new GridViewRow(0, 0, DataControlRowType.Header,
DataControlRowState.Insert);
DropDownList ddlFieldValues;
TableCell HeaderCell;
foreach (DataColumn dc in dtValues.Columns)
{
ddlFieldValues = new DropDownList();
ddlFieldValues.ID = "FieldValues";
ddlFieldValues.DataSource = (DataTable)Session["WorkItemTypeField"];
ddlFieldValues.DataTextField = "FieldName";
ddlFieldValues.DataValueField = "FieldID";
ddlFieldValues.DataBind();
ddlFieldValues.Items.Insert(0, new ListItem("", "0"));
HeaderCell = new TableCell();
HeaderCell.Controls.Add(ddlFieldValues);
HeaderGridRow.Cells.Add(HeaderCell);
}
gvDataMapping.DataSource = dtValues;
gvDataMapping.DataBind();
gvDataMapping.Visible = true;
lblDataMapping.Visible = true;
gvDataMapping.Controls[0].Controls.AddAt(1, HeaderGridRow);
See the Click here to view screen displays the output of above code . While clicking Save am not getting the GridView Header DropDowmList its showing null using below code.
GridViewRow gvrow2 = gvDataMapping.HeaderRow;
foreach (GridViewRow row in gvDataMapping.Rows)
{
for (int i = 0; i < gvDataMapping.Columns.Count; i++)
{
String header = gvDataMapping.Columns[i].HeaderText; //gets column name
DropDownList cellText = ((DropDownList)gvrow2.Cells[i].FindControl("FieldValues")); //Not getting the DDL returns null
}
}
How to get the GridView Header row dropdownlist values in Save click event?

No guarantees, because I haven't tried this myself, but what about this code?
GridViewRow gvrow1 = GrdDynamic1.HeaderRow;
foreach (GridViewRow row in GrdDynamic1.Rows)
{
for (int i = 0; i < GrdDynamic1.Columns.Count; i++)
{
String header = GrdDynamic1.Columns[i].HeaderText;
DropDownList cellText = ((DropDownList)gvrow1.Cells[i].FindControl("FieldValues"));
}
}
It looks as if you're looking for the drop down list in the right column, but not the right row: you're looking in the data row, rather than the header row gvrow1.

Related

Fill listview from SQL Server data

I have problem with creating listview I have tried different methods of filling ListView items from SQL Server and I can not solve it.
I created this function to fill the listview dynamically, the connection works so far, so thats not the problem. But currently my problem is, the function creates the row but they remain Empty while the header list work correctly.
I am writing the following code
XAML:
<ListView Name="LV" Height="494" Margin="10,30,10,10">
<ListView.View>
<GridView>
<GridViewColumn/>
</GridView>
</ListView.View>
</ListView>
C#
SqlDataAdapter sqladp = new SqlDataAdapter(query, strCon);
DataSet ds = new DataSet();
sqladp.Fill(ds, dValue);
DataTable dt = ds.Tables[0];
// Add columns
var gridView = new GridView();
LV.View = gridView;
for (int i = 0; i < dt.Columns.Count; i++)
{
gridView.Columns.Add(new GridViewColumn
{
Header = dt.Columns[i].ToString(),
DisplayMemberBinding = new Binding($"[{i}]")
});
}
if (dt.Rows.Count > 0)
//Add Row
foreach (DataRow row in dt.Rows)
{
string[] arr = new string[dt.Columns.Count];
ListViewItem itm;
try
{
for (int i = 0; i < dt.Columns.Count; i++)
arr[i] = row[i].ToString();
LV.Items.Add(arr);
}
catch
{
}
}
LV.Visibility = Visibility.Visible;
You're assigning rowItems to Content, but rowItems is empty and remains empty. Perhaps you meant to assign Content to arr, which you fill up but then do nothing with it.
Also, you don't need to create the ListViewItems yourself. They're created for you when you add items to the ListView.Items property. Change that part of the code to the following (based on your updated code):
for (int i = 0; i < dt.Columns.Count; i++)
arr[i] = row[i].ToString();
LV.Items.Add(arr);
Finally, because you're adding an array (rather than an object with properties), you need to fix the column's binding to the following:
gridView.Columns.Add(new GridViewColumn
{
Header = dt.Columns[i].ToString(),
DisplayMemberBinding = new Binding($"[{i}]")
});

Selecting a dynamically created table row in ASP.NET with C#

I am writing a web application in Visual Studio 2015 pro using C# and ASP.NET. Right now, I have it set up where the user will click a button and the C# code will go get a bunch of data then display it back to the user in tables. I have spent a day of work trying to figure out how to add some form of a clickable event to the table rows but have had no success. Ultimately, what I want to do is call a method in my C# code when the table row is clicked and send it the row index.
Here is the C# code I am using for generating the tables:
protected void searchButton_Click(object sender, EventArgs e)
{
try
{
// Remove the error display
resultListLabel.Style.Add("Display", "None");
// Get document groups
groups = TableCommands.getGroups(dbConn, "retriever", searchTextOne.Text, searchTextTwo.Text);
foreach (var dataPair in groups)
{
// Get data pair group names into list
List<string> name = dataPair.Key.Split('|').ToList();
// ====== Make table
Table resultTable = new Table();
resultTable.Attributes["class"] = "displayTable";
resultList.Controls.Add(resultTable);
// ====== Add table info row
TableRow groupInfo = new TableRow();
groupInfo.Attributes["class"] = "groupInfoLabel";
// add row to table
resultTable.Rows.Add(groupInfo);
// create cell with information
TableCell infoCell = new TableCell();
infoCell.Text = "MRN: "+name[0]+", Name: " + name[1];
infoCell.ColumnSpan = 3;
// add cell to row
groupInfo.Cells.Add(infoCell);
// ====== Make column label row
TableRow labelRow = new TableRow();
labelRow.Attributes["class"] = "columnLabel";
// add row to table
resultTable.Rows.Add(labelRow);
// make an array of column lables
string[] cellNames = new string[] { "Visit Date", "Document Type", "Doctor ID" };
// add column lables to row
foreach (string s in cellNames)
{
TableCell labelCell = new TableCell();
labelCell.Text = s;
labelRow.Cells.Add(labelCell);
}
// Add display names to table
foreach(var nameList in dataPair.Value)
{
TableRow nameRow = new TableRow();
nameRow.Attributes["class"] = "columnInfo";
for (int i = 0; i < 3; i++)
{
TableCell nameCell = new TableCell();
nameCell.Text = nameList[i];
nameRow.Cells.Add(nameCell);
}
resultTable.Rows.Add(nameRow);
}
}
}
catch(Exception ex)
{
// Display the error and write to log
resultListLabel.Style.Add("Display", "Inline-Block");
writeLog("Failed to generate tables", ex.ToString());
}
}
Here's what I had to do:
Add a global boolean to called tableCall to the C# code
Move the code in searchButton_Click into an if(tableCall) statement in the Page_Load method.
protected void Page_Load(object sender ,EventArgs e){
...
if(tableCall){
//Do stuff from searchButton_Click
}
...
}
Add tableCall = true; and Page_Load(sender, e) to searchButton_Click
Modify the for loop to add buttons in the cell like so:
// Add display names to table
foreach (var nameList in dataPair.Value)
{
TableRow nameRow = new TableRow();
nameRow.Attributes["class"] = "columnInfo";
// Add display names to table
foreach (var nameList in dataPair.Value)
{
TableRow nameRow = new TableRow();
nameRow.Attributes["class"] = "columnInfo";
for (int i = 0; i < 3; i++)
{
TableCell nameCell = new TableCell();
nameRow.Cells.Add(nameCell);
Button b = new Button();
b.Attributes["class"] = "docButton";
b.Attributes.Add("DWdocid", nameList[3]);
b.Text = nameList[i];
b.Click += new EventHandler((s, ea) => test(s, ea, b.Attributes["DWdocid"]));
nameCell.Controls.Add(b);
}
resultTable.Rows.Add(nameRow);
}
This adds a button to each of the three cells in the row, but adds the same document id to each of the buttons in that row, so anywhere the user clicks on that row (except for the 1px borders) will call a method in the C# code while passing it the document ID. I'm sure that with better css skills somebody could make the button span all three cells.

c# how to set several combobox column in datagridview

I have been able to make one existing column combo box column in the datagridview, how do I do it for several columns? Also how do I add existing distinct records in the combobox items? The user will be able to either choose value from combobox item or write their own. So far my code is:
dgvLoadTable.DataSource = null;
var context = new CadAdminEntities();
var TableName = cboSelectTable.Text.ToString();
var rawData = context.GetType().GetProperty(TableName).GetValue(context, null);
var truncatedData = ((IQueryable<object>)rawData).Take(0);
var source = new BindingSource { DataSource = truncatedData };
dgvLoadTable.DataSource = source;
dgvLoadTable.ReadOnly = false;
dgvLoadTable.AllowUserToAddRows = true;
DataGridViewComboBoxCell dgvCol = new DataGridViewComboBoxCell();
for (int row= 0; row < dgvLoadTable.Rows.Count; row++)
{
for (int col = 0; col < dgvLoadTable.Columns.Count; col++)
{
if(col==2||col==4)
this.dgvLoadTable[col,row] = dgvCol;
//This part throws error, as there is only one combobox
}
}
dgvLoadTable.Refresh();
This is easy to fix:
this.dgvLoadTable[col, row] = new DataGridViewComboBoxCell();
will create a fresh ComboBoxCell for each case.
You can delete the line
DataGridViewComboBoxCell dgvCol = new DataGridViewComboBoxCell();
Note that since you have a Databound DGV and the Columns were probably created automatically, you should keep in mind, that often one needs to switch off that automatism and create all column manually before setting the DataSource..

Get selected items in a RadGrid client-side

I want to get the values of the selected checkbox in a RadGrid.
I have a radgrid, textbox and a button as follows:
this._RadAjaxPanel.Controls.Add(RadGrid1);
this._RadAjaxPanel.Controls.Add(TextBox1);
this._RadAjaxPanel.Controls.Add(Buton1);
The radgrid id is set to RadGrid1 and
Button1.OnClientClick = "GetSelectedItems("+ this._RadGrid1 +")";
On click of the button a javascript is called where I want to know which rows have been selected.
The javascript function is as follows but it is not correct:
function GetSelectedItems(grid) {
var selectedRows = grid.get_selectedItems();
for (var i = 0; i < selectedRows.length; i++) {
var row = selectedRows[i];
var cell = grid.getCellByColumnUniqueName(row, "CategoryID")
//here cell.innerHTML holds the value of the cell
}
}
Please let me know how can I get the selected rows.
Here is how to get whether or not a checkbox is selected. I am using a GridTemplateColumn with a CheckBox as the ItemTemplate, which Telerik always suggests using over the GridCheckBoxColumn.
The trick is to get the inner HTML in the cell, and parse out the name of the control. The cell value will be something like id=cbxRow where the CheckBox control's ID is cbxRow like in the below example.
JavaScript:
var grid = $find("RadGrid1");
var masterTableView = grid.get_masterTableView();
var selectedRows = masterTableView.get_selectedItems();
for (var i = 0; i < selectedRows.length; i++) {
var cellCB = masterTableView.getCellByColumnUniqueName(row, "CB");
var innerCB = cellCB.innerHTML;
var locId = innerCB.indexOf("id=");
var locIdEnd = innerCB.indexOf("\" ", locId);
var idVal = innerCB.substr(locId + 4, locIdEnd - locId - 4);
var cbx = document.getElementById(idVal);
if (cbx.checked) {
alert("The checkbox is checked!");
}
else {
alert("The checkbox is not checked!");
}
}
ASPX:
<telerik:GridTemplateColumn UniqueName="CB" ...>
<ItemTemplate>
<asp:CheckBox ID="cbxRow" runat="server">
</ItemTemplate>
</telerik:GridTemplateColumn>
I have tried the following, which solved my issue:
this._Button1.Attributes.Add("OnClick", "GetSelectedItems('" + _RadGrid1.ClientID + "');return false;");

Grid View Button Passing Data Via On Click

I'm pretty new to C# and asp.net so apologies if this is a really stupid question.
I'm using a grid view to display a number of records from a database.
Each row has an Edit Button. When the button is clicked I want an ID to be passed back to a function in my .cs file. How do I bind the rowID to the Button field?
I've tired using a hyper link instead but this doesn't seem to work because I'm posting back to the same page which already has a Permanter on the URL.
asp.net
<asp:GridView ID="gvAddresses" runat="server" onrowcommand="Edit_Row">
<Columns>
<asp:ButtonField runat="server" ButtonType="Button" Text="Edit">
</Columns>
</asp:GridView>
c#
int ImplantID = Convert.ToInt32(Request.QueryString["ImplantID"]);
Session.Add("ImplantID", ImplantID);
List<GetImplantDetails> DataObject = ImplantDetails(ImplantID);
System.Data.DataSet DSImplant = new DataSet();
System.Data.DataTable DTImplant = new DataTable("Implant");
DSImplant.Tables.Add(DTImplant);
DataColumn ColPostCode = new DataColumn();
ColPostCode.ColumnName = "PostCode";
ColPostCode.DataType = typeof(string);
DTImplant.Columns.Add(ColPostCode);
DataColumn ColConsigneeName = new DataColumn();
ColConsigneeName.ColumnName = "Consignee Name";
ColConsigneeName.DataType = typeof(string);
DTImplant.Columns.Add(ColConsigneeName);
DataColumn ColIsPrimaryAddress = new DataColumn();
ColIsPrimaryAddress.ColumnName = "Primary";
ColIsPrimaryAddress.DataType = typeof(int);
DTImplant.Columns.Add(ColIsPrimaryAddress);
DataColumn ColImplantCustomerDetailsID = new DataColumn();
ColImplantCustomerDetailsID.ColumnName = "Implant ID";
ColImplantCustomerDetailsID.DataType = typeof(int);
DTImplant.Columns.Add(ColImplantCustomerDetailsID);
foreach (GetImplantDetails Object in DataObject)
{
DataRow DRImplant = DTImplant.NewRow();
DRImplant["PostCode"] = Object.GetPostCode();
DRImplant["Consignee Name"] = Object.GetConsigneeName();
DRImplant["Primary"] = Object.GetIsPrimaryAddress();
DRImplant["Implant ID"] = Object.GeTImplantCustomerDetailsID();
DTImplant.Rows.Add(DRImplant); <--- this is what I need to be added to the button
}
gvAddresses.DataSource = DTImplant;
gvAddresses.DataBind();
In your Edit_Row method you can access the index of the row you are editing like:
int rowIndex = (int)e.CommandArgument;
Once you have that you can access the row directly and pull out any values you want:
GridViewRow row = gvTest.Rows[rowIndex];
int implantId = Int32.Parse(string row.Cells[3].Text);
Alternatively, you can also add the property DataKeyNames="Implant ID" to your GridView and access the id that way:
int implantId = Int32.Parse(gvTest.DataKeys[rowIndex]["Implant ID"].ToString());

Categories

Resources