How do I format hyperlink column gridview in my codebehind file? - c#

I am trying to make a column a hyperlink in my grid view. I am Using Umbraco 6 childpages as datasource. I have a link but at the moment it's going to /website/masterpages/url with %20% in the spaces
My View is like this:
<asp:hyperlinkfield datatextfield="title" datanavigateurlfields="title" headertext="Title" />
and code behind like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
HyperLinkField title = new HyperLinkField();
string[] dataNavigateUrlFields = { "title" };
title.DataTextField = "title";
title.DataNavigateUrlFields = dataNavigateUrlFields;
title.HeaderText = "Title";
title.DataNavigateUrlFormatString = "item.Url";
// Create a BoundField object to display the company's city.
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("title", typeof(String)),
new DataColumn("lastUpdated", typeof(string)),
new DataColumn("theme",typeof(string)) });
int i = 0;
foreach (var item in uQuery.GetCurrentNode().ChildrenAsList)
{
var dateTimeString = item.GetProperty("lastUpdated").Value.ToString();
var dateTime = System.Xml.XmlConvert.ToDateTime(dateTimeString);
dt.Rows.Add(item.Name, dateTime.ToString("dd.MM.yyyy"), item.GetProperty("theme").Value.ToString());
}
Session["data"] = dt;
Cache["Data"] = dt;
Practice.DataSource = dt;
Practice.DataBind();
}
can anyone tell me what I'm doing wrong - thanks

I figured it out, but adding an extra column to the table called name (as this is not displayed unless you reference it on the output, removing:
HyperLinkField title = new HyperLinkField();
string[] dataNavigateUrlFields = { "title" };
title.DataTextField = "title";
title.DataNavigateUrlFields = dataNavigateUrlFields;
title.HeaderText = "Title";
title.DataNavigateUrlFormatString = "item.Url";
// Create a BoundField object to display the company's city.
and changing the datatextfield to "name" ie DataTextField="name".
If anyone else gets stuck:)

Related

ComboBox added programmatically to DataGridView cell not expanding on cell click

I have a DataGridView in a C# WinForms project in which, when the user clicks on certain DGV cells, the cell changes to a DataGridViewComboBoxCell and the ComboBox is populated with some values for the user to select. Here's the form code for the DataGridView_Click event:
private void dgvCategories_Click(Object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 5 && !(dgvCategories.Rows[e.RowIndex].Cells[e.ColumnIndex].GetType().Name == "DataGridViewComboBoxCell"))
{
// Bind combobox to dgv and than bind new values datasource to combobox
DataGridViewComboBoxCell cboNewValueList = new DataGridViewComboBoxCell();
// Get fields to build New Value query
List<string> lsNewValuesResult = new List<string>();
string strCategory = dtCategories.Rows[e.RowIndex][1].ToString();
string strCompanyName = cboSelectCompany.Text;
string strQueryGetNewValuesValidationInfo = "SELECT validationdb, validationtable, validationfield, validationfield2, validationvalue2" +
" FROM masterfiles.categories" +
" WHERE category = #category";
//" WHERE category = '" + strCategory + "'";
// Pass validation info query to db and return list of New Values
db getListOfNewValues = new db();
lsNewValuesResult = getListOfNewValues.GetNewValuesList(strQueryGetNewValuesValidationInfo, strCategory, strCompanyName);
//Populate the combobox with the list of New Values
foreach (string strListItem in lsNewValuesResult)
{
cboNewValueList.Items.Add(strListItem);
}
//
dgvCategories[e.ColumnIndex, e.RowIndex] = cboNewValueList;
}
}
Here's the code in the db class that populates the ComboBox (this likely isn't necessary to include for the purposes of this question, but for the sake of completeness, I'm including it, in case is it relevant):
public List<string> GetNewValuesList(string strValidationInfoQuery, string strCategory, string strCompanyName)
{
List<string> lsValidationInfo = new List<string>();
List<string> lsNewValuesList = new List<string>();
using (NpgsqlConnection conn = new NpgsqlConnection(connString))
using (NpgsqlCommand cmd = new NpgsqlCommand(strValidationInfoQuery, conn))
{
cmd.Parameters.AddWithValue("category", strCategory);
conn.Open();
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int intReaderIndex;
for (intReaderIndex = 0; intReaderIndex <= reader.FieldCount - 1; intReaderIndex++)
{
// reader indexes 3 & 4 correspond to categories.validationfield2 and validationvalue2, which can be null
if (string.IsNullOrEmpty(reader[intReaderIndex].ToString()))
{
lsValidationInfo.Add("");
}
else
{
lsValidationInfo.Add(reader.GetString(intReaderIndex));
}
//Console.WriteLine("reader index " + intReaderIndex + ": " + reader.GetString(intReaderIndex));
}
}
}
}
string strValidationDb = lsValidationInfo[0];
string strValidationTable = lsValidationInfo[1];
string strValidationField = lsValidationInfo[2];
string strValidationField2 = lsValidationInfo[3];
string strValidationValue2 = lsValidationInfo[4];
string strQueryGetNewValues = "SELECT DISTINCT " + strValidationField +
" FROM " + strValidationDb + "." + strValidationTable +
" WHERE company_id = (SELECT id FROM company WHERE name = '" + strCompanyName + "')";
if (!string.IsNullOrEmpty(strValidationField2) && !string.IsNullOrEmpty(strValidationValue2)) strQueryGetNewValues += " AND " + strValidationField2 + " = '" + strValidationValue2 + "'";
strQueryGetNewValues += " ORDER BY " + strValidationField;
using (NpgsqlConnection conn = new NpgsqlConnection(connString))
using (NpgsqlCommand cmd = new NpgsqlCommand(strQueryGetNewValues, conn))
{
conn.Open();
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int intReaderIndex;
for (intReaderIndex = 0; intReaderIndex <= reader.FieldCount - 1; intReaderIndex++)
{
// reader indexes 3 & 4 correspond to categories.validationfield2 and validationvalue2, which can be null
if (string.IsNullOrEmpty(reader[intReaderIndex].ToString()))
{
lsNewValuesList.Add("");
}
else
{
lsNewValuesList.Add(reader.GetString(intReaderIndex));
}
Console.WriteLine("reader index " + intReaderIndex + ": " + reader.GetString(intReaderIndex));
}
}
}
}
return lsNewValuesList;
}
The combobox is getting populated, as I can access the items in lsNewValuesResult in the _Click method. The DGV Edit Mode is set to EditOnEnter. I tried EditOnKeystroke, but that didn't cause the combobox to expand on mouse click.
This is what the combobox looks like when the cell is clicked on and the CBO is populated and added to the DGV cell:
That's after I clicked each of the two cells.
[RESOLVED]
See my Answer below.
Unfortunately solving this revealed a new issue.
I'm about to publicly admit that I'm stupid:
For design and functionality reasons that are required for this project, I am manually setting the widths and names of the DGV's columns, and I also need the 2nd through 4th columns ReadOnly = true. Well, I inadvertently set the 5th column - the column that this question is about to ReadOnly = true as well.
Thank you all for your attempts at answering. This just serves to remind us how something so simple can cause a seemingly big issue and is so easy to overlook!
If I recognize your problem correctly, in my test app i add a DataGridView whit 6 column, EditMode = EditOnEnter
(Others need three time click to open dropdown, As far as I tried) and handle CellStateChanged envent.
private void dgvCategories_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
if (e.StateChanged == DataGridViewElementStates.Selected)
{
DataGridViewCell cell = e.Cell;
int columnIndex = cell.ColumnIndex;
int rowIndex = cell.RowIndex;
//---IF CONDITIONS--
//columnIndex == 5
// Only cells in Columns[5]
//cell.Selected
// Because this event raised two time, first for last selected cell and once again
// for currently selected cell and we need only currently selected cell.
//cell.EditType.Name != "DataGridViewComboBoxEditingControl"
// If this cell "CellStateChanged" raised for second time, only other cell types allowed
// to edit, otherwise the current cell lost last selected item.
if (columnIndex == 5 && cell.Selected && cell.EditType.Name != "DataGridViewComboBoxEditingControl")
{
DataGridViewComboBoxCell cboNewValueList = new DataGridViewComboBoxCell();
//Add items to DataGridViewComboBoxCell for test, replace it with yours.
for (int i = 0; i < 10; i++)
cboNewValueList.Items.Add($"Item {i}");
dgvCategories[columnIndex, rowIndex] = cboNewValueList;
}
}
}
NOTE: user must click two time in a cell to open drop down menu.
Edit One: As Reza Aghaei suggest for single click in cell:
private void dgvCategories_CellClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewComboBoxEditingControl editingControl = dgvCategories.EditingControl as DataGridViewComboBoxEditingControl;
if (editingControl != null)
editingControl.DroppedDown = true;
}
You might need to turn AutoGenerateColumns off:
Also, it seems to take a three clicks for the dropdown to pop.
public Form1()
{
InitializeComponent();
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = GetDataSource();
DataGridViewComboBoxColumn dgvcbc = new DataGridViewComboBoxColumn();
dgvcbc.Items.Add("R0C0");
dgvcbc.Items.Add("R1C0");
dgvcbc.Items.Add("R2C0");
dgvcbc.Items.Add("R3C0");
dgvcbc.DataPropertyName = "Col0";
dataGridView1.Columns.Add(dgvcbc);
}
DataTable GetDataSource()
{
var dtb = new DataTable();
dtb.Columns.Add("Col0", typeof(string));
dtb.Columns.Add("Col1", typeof(string));
dtb.Columns.Add("Col2", typeof(string));
dtb.Columns.Add("Col3", typeof(string));
dtb.Columns.Add("Col4", typeof(string));
dtb.Rows.Add("R0C0", "R0C1", "R0C2", "R0C3", "R0C4");
dtb.Rows.Add("R1C0", "R1C1", "R1C2", "R1C3", "R1C4");
dtb.Rows.Add("R2C0", "R2C1", "R2C2", "R2C3", "R2C4");
dtb.Rows.Add("R3C0", "R3C1", "R3C2", "R3C3", "R3C4");
return dtb;
}
Are you maybe getting an error which is not being shown for some reason?
If I use your code, DataGridViewComboBoxCell seems to be populated with values, but I get DataGridViewComboBoxCell value is not valid runtime error.
This test code is working fine for me:
private void dgvCategories_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewComboBoxCell cboNewValueList = new DataGridViewComboBoxCell();
List<string> lsNewValuesResult = new List<string>();
lsNewValuesResult.Add("Value1");
lsNewValuesResult.Add("Value2");
lsNewValuesResult.Add("Value3");
foreach (string strListItem in lsNewValuesResult)
{
cboNewValueList.Items.Add(strListItem);
}
dgvCategories[e.ColumnIndex, e.RowIndex] = cboNewValueList;
// Added setting of initial value
cboNewValueList.Value = cboNewValueList.Items[0];
}
So maybe try setting the initial value for your DataGridViewComboBoxCell after you add it to the DataGridView.
You can consider the following facts about DataGridView:
If you set AutoGenerateColumns to false, then you need to add columns to Columns collection manually.
If you set AutoGenerateColumns to true, when you assign the data to DataSource, the control generates columns automatically for the data source. In this case, the control looks in list of columns of the data source and for each column if there's no column in the Columns collection of the control having the same DataPropertyName as data source's column name, it will add a column to Columns collection.
DataPropertyName of the datagridviews' columns determines the bound column of the data source.
You usually want to add DataGridViewXXXXColumn to columns collection rather than using a DataGridViewXXXXCell for a cell.
If you set EditMode to EditOnEnter, then if you click on dropdown button, one click is enough. If you click on cell content, two clicks is needed.
If you would like to make it single click even if you click on cell content, take a look at this post. (Note: I haven't used this is the example, it's a bit annoying.)
you can set DisplayStyle to Nothing, then it shows the column as a combo box, just in edit mode.
A basic example on using DataGridViewComboBoxColumn
I suppose you are going to show a list of Products having (Id, Name, Price, CategoryId) in a DataGridView and the CategoryId should come from a list of Categories having (Id, Name) and you are going to show CategoryId as a ComboBox.
In fact it's a basic and classic example of DataGridViewComboBoxColumn:
private void Form1_Load(object sender, EventArgs e) {
var categories = GetCategories();
var products = GetProducts();
var idColumn = new DataGridViewTextBoxColumn() {
Name = "Id", HeaderText = "Id", DataPropertyName = "Id"
};
var nameColumn = new DataGridViewTextBoxColumn() {
Name = "Name", HeaderText = "Name", DataPropertyName = "Name"
};
var priceColumn = new DataGridViewTextBoxColumn() {
Name = "Price", HeaderText = "Price", DataPropertyName = "Price"
};
var categoryIdColumn = new DataGridViewComboBoxColumn() {
Name = "CategoryId", HeaderText = "Category Id", DataPropertyName = "CategoryId",
DataSource = categories, DisplayMember = "Name", ValueMember = "Id",
DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
};
dataGridView1.Columns.AddRange(idColumn, nameColumn, priceColumn, categoryIdColumn);
dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = products;
}
public DataTable GetProducts() {
var products = new DataTable();
products.Columns.Add("Id", typeof(int));
products.Columns.Add("Name", typeof(string));
products.Columns.Add("Price", typeof(int));
products.Columns.Add("CategoryId", typeof(int));
products.Rows.Add(1, "Product 1", 100, 1);
products.Rows.Add(2, "Product 2", 200, 2);
return products;
}
public DataTable GetCategories() {
var categories = new DataTable();
categories.Columns.Add("Id", typeof(int));
categories.Columns.Add("Name", typeof(string));
categories.Rows.Add(1, "Category 1");
categories.Rows.Add(2, "Category 2");
return categories;
}
Learn more
To learn more about DataGridView, take a look at DataGridView Control (Windows Forms). It contains links to some documentations and useful How To articles, including:
DataGridView Control Overview
Basic Column, Row, and Cell Features in the Windows Forms DataGridView Control
Basic Formatting and Styling in the Windows Forms DataGridView Control
Column Types in the Windows Forms DataGridView Control

How to get value of a programmatically written combobox in a datagrid in wpf?

To follow my previous post here => Binding SelectedItem of ComboBox in DataGrid with different type
I have now a datagrid containing 2 columns, one with a text, the other with a combobox (in a datatemplate, written thru the C# code, not the Xaml).
After having done some choice on the combobox, I now would like to parse the result but the value of the cell containing my combobox stay empty :
foreach(DataRowView row in Datagrid1.Items)
{
var firstColumNresult = row.Row.ItemArray[0];// Return correctly a string
var myrow = row.Row.ItemArray[1];// always empty...
}
The result is that I cant get the values of my (previously generated) combobox.
I suppose one binding must missed somewhere...
This is the combobox creation code :
DataTable tableForDG = new DataTable();
tableForDG.Columns.Add(new DataColumn { ColumnName = "Name", Caption = "Name" });
tableForDG.Columns.Add(new DataColumn { ColumnName = "Attachment", Caption = "Attachment" }); // this column will be replaced
tableForDG.Columns.Add(new DataColumn { ColumnName = "AttachmentValue", Caption = "AttachmentValue" });
tableForDG.Columns.Add(new DataColumn { ColumnName = "DisplayCombo", Caption = "DisplayCombo", DataType=bool });
// Populate dataview
DataView myDataview = new DataView(tableForDG);
foreach (var value in listResults)// a list of string
{
DataRowView drv = myDataview.AddNew();
drv["Name"] = value.Name;
drv["Attachment"] = value.Name;// this column will be replaced...
drv["DisplayCombo"] = true;// but it can be false on my code...
}
var DG = myDataview;//
Datagrid1.ItemsSource = DG;
Datagrid1.AutoGenerateColumns = true;
Datagrid1.Items.Refresh();
DataGridTemplateColumn dgTemplateColumn = new DataGridTemplateColumn();
dgTemplateColumn.Header = "Attachment";
var newCombobox = new FrameworkElementFactory(typeof(ComboBox));
newCombobox.SetValue(ComboBox.NameProperty, "myCBB");
Binding enableBinding = new Binding();
newCombobox.SetValue(ComboBox.IsEnabledProperty, new Binding("DisplayCombo"));
newCombobox.SetValue(ComboBox.SelectedValueProperty, new Binding("AttachmentValue"));
List<string> listUnitAlreadyAttached = new List<string>();
// fill the list...
enableBinding.Source = listUnitAlreadyAttached;
newCombobox.SetBinding(ComboBox.ItemsSourceProperty, enableBinding);
var dataTplT = new DataTemplate();
dataTplT.VisualTree = newCombobox;
dgTemplateColumn.CellTemplate = dataTplT;
Datagrid1.Columns[1] = dgTemplateColumn;
Any idea/advice ?
You should explicitely specify the binding mode and update trigger of your binding. Also use SetBinding instead of SetValue:
var valueBinding = new Binding("AttachmentValue")
{
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
newCombobox.SetBinding(ComboBox.SelectedValueProperty, valueBinding);
This should enable you to get the selected value into your row data. It might not update in the displayed datagrid value for the AttachmentValue column.

How to set a DataGridView column to a DataGridViewComboBoxColumn?

Here is my code:
DataSet data = new DataSet();
data.ReadXml("data.xml");
DataGridView grid = new DataGridView();
var genreCboBoxItems = data.Tables[0].AsEnumerable().Select(genre => genre.Field<string>("genre")).Distinct().ToArray();
// TODO: Make is so the 'genre' column in grid is a combo box?
grid.DataSource = data.Tables[0];
grid.Dock = DockStyle.Fill;
this.Controls.Add(grid);
*edit: genreCboBoxItems
Try this: (not tested)
var column = new DataGridViewComboBoxColumn();
column.DataSource = data.Tables[0].AsEnumerable().
Select(genre => new { genre = genre.Field<string>("genre") }).Distinct();
column.DataPropertyName = "genre";
column.DisplayMember = "genre";
column.ValueMember = "genre";
grid.DataSource = data.Tables[0];
// Instead of the below line, You could use grid.Columns["genre"].Visible = false;
grid.Columns.Remove("genre");
grid.Columns.Add(column);
This might help you cast DataGridViewColumn to DataGridViewComboBox.
First create DataGridViewComboBoxColumn using designer with proper name. Then say you have a list of String list and other string values to bind to that datagridview then use this code:
Below code will bind a list to two DataGridViewTextBoxCell and a DataGridViewComboBoxCell. Note AllCriterias is a list with two string values and a list of string. DGVEligibilityCriteria is the grid name.
for (int i = 0; i < AllCriterias.Count; i++)
{
DataGridViewTextBoxCell Cmb1 = (DataGridViewTextBoxCell)DGVEligibilityCriteria.Rows[i].Cells[0];
Cmb1.Value = AllCriterias[i].Name;
DataGridViewTextBoxCell Cmb2 = (DataGridViewTextBoxCell)DGVEligibilityCriteria.Rows[i].Cells[1];
Cmb2.Value = AllCriterias[i].Type;
DataGridViewComboBoxCell Cmb = (DataGridViewComboBoxCell)DGVEligibilityCriteria.Rows[i].Cells[2];
foreach (var filtervalue in AllCriterias[i].FilterValues)
{
Cmb.Items.Add(filtervalue);
}
}
Need to display the fist index as default by setting selectindex property.
Use this code : Here "filterValues" is the name of the DataGridViewComboBoxCell which u created in the datagridview designer.
foreach (DataGridViewRow row in DGVEligibilityCriteria.Rows)
{
row.Cells["filterValues"].Value = (row.Cells["filterValues"] as DataGridViewComboBoxCell).Items[0];
}

How to add new items to combobox which is bound to Entities?

Design class which is generated by C# :
//
// usepurposeComboBox
//
this.usepurposeComboBox.DataSource = this.usepurposeBindingSource;
this.usepurposeComboBox.DisplayMember = "Name";
this.usepurposeComboBox.FormattingEnabled = true;
this.usepurposeComboBox.Location = new System.Drawing.Point(277, 53);
this.usepurposeComboBox.Name = "usepurposeComboBox";
this.usepurposeComboBox.Size = new System.Drawing.Size(218, 21);
this.usepurposeComboBox.TabIndex = 4;
this.usepurposeComboBox.ValueMember = "id";
//
// usepurposeBindingSource
//
this.usepurposeBindingSource.DataSource = typeof(mydatabaseEntities.usepurpose);
Then I bound the BindingSource (usepurposeBindingSource) to Entities :
usepurposeBindingSource.DataSource = mydatabaseEntities.usepurposes;
And I can not add a new row to usepurposeComboBox because it's been bound. Is there a workaround ?
The shortest way is to add a new row to your dataTable and then bind your comboBox to it something like this:
Company comps = new Company();
//pupulate dataTable with data
DataTable DT = comps.getCompaniesList();
//create a new row
DataRow DR = DT.NewRow();
DR["c_ID"] = 0;
DR["name"] = "Add new Company";
DR["country"] = "IR";
//add new row to data table
DT.Rows.Add(DR);
//Binding DataTable to cxbxCompany
cxbxCompany.DataSource = DT;
cxbxCompany.DisplayMember = "name";
cxbxCompany.ValueMember = "c_ID";
I'm assuming that you want to add for example a first item sometimes called "Choose One" as if you want to live data you should just see where the data comes from and add more items to that "table".
this.usepurposeBindingSource is an object ... why not adding into it before it binds?
if it's a List<T> this will be fine
this.usepurposeBindingSource.Insert(0, new T() {
Name = "Choose one",
Id = ""
});
Then Bind() it...
Remember to validate as it's a string and will not be the object you want
This is working:
List<MyObject> usepurposeBindingSource { get; set; }
private void FillUpData()
{
// Simulating an External Data
if (usepurposeBindingSource == null || usepurposeBindingSource.Count == 0)
{
this.usepurposeBindingSource = new List<MyObject>();
this.usepurposeBindingSource.Add(new MyObject() { Name = "A", ID = 1 });
this.usepurposeBindingSource.Add(new MyObject() { Name = "B", ID = 2 });
this.usepurposeBindingSource.Add(new MyObject() { Name = "C", ID = 3 });
}
}
private void FillUpCombo()
{
FillUpData();
// what you have from design
// comment out the first line
//this.usepurposeComboBox.DataSource = this.usepurposeBindingSource;
this.usepurposeComboBox.DisplayMember = "Name";
this.usepurposeComboBox.FormattingEnabled = true;
this.usepurposeComboBox.Location = new System.Drawing.Point(277, 53);
this.usepurposeComboBox.Name = "usepurposeComboBox";
this.usepurposeComboBox.Size = new System.Drawing.Size(218, 21);
this.usepurposeComboBox.TabIndex = 4;
this.usepurposeComboBox.ValueMember = "id";
// to do in code:
this.usepurposeBindingSource.Insert(0, new MyObject() { Name = "Choose One", ID = 0 });
// bind the data source
this.usepurposeComboBox.DataSource = this.usepurposeBindingSource;
}
The trick is to comment out the DataSource line and do it in your code, inserting one more element into your object that is from your Model
//this.usepurposeComboBox.DataSource = this.usepurposeBindingSource;
The simplest way to do this, is to wrap your BindingSource with some kind of "ViewModel". The new class will return a "complete" list of items - both those provided from the original binding source, as well as those "additional" items.
You can then bind the new wrapper to your combobox.
I wrote an article about this a while back... It's not my finest work, and it's probably a bit outdated, but it should get you there.
I resolved it on my own. I created a new unbound combobox then bind it to a datatable. Not sure if it's the best way but it works for me. Thanks for all of your suggestions. :)
private void FillCombobox()
{
using (mydatabaseEntities mydatabaseEntities = new mydatabaseEntities())
{
List<usepurpose> usepurposes = mydatabaseEntities.usepurposes.ToList();
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("Name");
dt.Rows.Add(-1, "test row");
foreach (usepurpose usepurpose in usepurposes)
{
dt.Rows.Add(usepurpose.id, usepurpose.Name);
}
usepurposeComboBox.ValueMember = dt.Columns[0].ColumnName;
usepurposeComboBox.DisplayMember = dt.Columns[1].ColumnName;
usepurposeComboBox.DataSource = dt;
}
}
Check out this link: http://forums.asp.net/t/1695728.aspx/1?
In asp you can add this to insert an empty line:
<asp:DropDownList ID="CustomerDropDownList" runat="server"
DataSourceID="CustomerEntityDataSource" DataTextField="CustomerId"
DataValueField="CustomerId" AppendDataBoundItems="true">
<asp:ListItem Text="Select All Customers" Value="" />
</asp:DropDownList>
Or in code behind:
DropDownList1.AppendDataBoundItems = true;
DropDownList1.Items.Add(new ListItem("Select All Customers", "-1"));

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