I am trying to get one column from my datatable to be displayed as a combo box in my grid view. Also need to have the ability to fill the combo with a small collection to chose from. It will not show the values when i bind it from the Gui so I am trying it programmatic but cant seem to find the right code.
connection2 = new MySqlConnection(ConnectionString2);
try
{
string proid = txtbxProjId.Text;
//prepare query to get all records from items table
string query2 = "select sl.sample_id As sample_id, sl.sample_number As Sample_Number, sl.sample_date As Sample_Date, sl.sample_time As Sample_Time, sl.sample_comments As Sample_Comments FROM spt_sample_login sl Where project_id = '"+proid+"'";
//prepare adapter to run query
adapter2 = new MySqlDataAdapter(query2, connection2);
adapter3 = new MySqlDataAdapter(query2, connection2);
//create a DataTable to hold the query results
DataTable dTable2 = new DataTable();
DataSet DS2 = new DataSet();
//fill the DataTable
//get query results in dataset
adapter2.Fill(dTable2);
adapter3.Fill(DS2);
//return datatable with all records
//BindingSource to sync DataTable and DataGridView
//set the BindingSource DataSource
GridView1.DataSource = dTable2;
this.GridView1.Columns["sample_id"].Visible = false;
this.GridView1.Columns["Sample_Type"].DisplayIndex = 4;
this.GridView1.Columns["Sample_Type"].Visible = true;
//set the DataGridView DataSource
}
catch (MySqlException ex)
{
}
}
This works but shows the Sample_Type as a text box where i want it to be a combo with F,P Q,B as options.
Thank you
Brent
You have to put your ComboBox in a itemTemplate, and you have to fill it during rowDataBound event.
Quick exemple from my current project:
DropDownList ddlRole = (DropDownList)e.Row.FindControl("ddlRole");
ddlRole.DataSource = GetTruckersRoles();
string[] rolesList = Roles.GetRolesForUser((string)gvTruckers.DataKeys[e.Row.RowIndex][0]);
if (rolesList.Length > 0)
{
//If user is not in any roles, dont' do this
ddlRole.SelectedValue = rolesList[0];
}
ddlRole.DataBind();
Just adapt the code to your situation
Related
Basically I have a gridview with 2 columns (id, years). When there is no data for the source of this gridview, I want to show header and footer rows and inside the gridview, a message will be displayed to the user (NO RECORDS FOUND).
I have already tried using gridview properties ShowHeaderWhenEmpty="true" and EmptyDataText="no records found". This method does show the message but as gridview is empty so it won't show the footer row.
Here is result:
enter image description here
Then I read somewhere that I should add an empty dummy row to gridview when gridview is empty and I also tried that, now it does show header and footer and also show the message but one small problem is that the message is shown only in first column if gridview and others columns are shown empty
enter image description here
Here is code behind used for above image
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
public void BindGridview()
{
//if datatable has rows meaning data source is not empty
if(((DataTable)this.Get_Details()).Rows.Count > 0)
{
GridView1.DataSource = this.Get_Details();
GridView1.DataBind();
}
else
{
//if the Data is empty then bind the GridView with an Empty Dataset
GridView1.DataSource = this.Get_EmptyDataTable();
GridView1.DataBind();
}
}
public DataTable Get_Details()
{
DataTable dt = new DataTable();
string cs = WebConfigurationManager.ConnectionStrings["USTB-OBE-DATABASE"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
string query = "select * from test3";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
con.Open();
cmd.ExecuteNonQuery();
dt = ds.Tables[0];
}
return dt;
}
public DataTable Get_EmptyDataTable()
{
DataTable datatableEmpty = new DataTable();
//Here ensure that you have added all the column available in your gridview
datatableEmpty.Columns.Add("id", typeof(string));
datatableEmpty.Columns.Add("year", typeof(int));
DataRow dataRow = datatableEmpty.NewRow();
//Inserting a new row,datatable .newrow creates a blank row
dataRow[0] = "no records found";
datatableEmpty.Rows.Add(dataRow);//adding row to the datatable
return datatableEmpty;
}
}
But I actually want that both columns are col-spanned and whole row is shown as single column and message is displayed inside meaning that I want this enter image description here result but i also want the footer to be displayed also.
I would really appreciate if anyone could help.
After you have bound the empty data table, modify the cells themselves. Set the colspan of the first cell to "2", and then delete the second cell.
GridView1.DataSource = this.Get_EmptyDataTable();
GridView1.DataBind();
GridView1.Rows[0].Cells[0].Attributes["colspan"] = "2";
GridView1.Rows[0].Cells.RemoveAt(1);
I think your empty DataTable should be like this.
DataTable dt = new DataTable(); // Data table creation without any rows
GridView1.DataSource = dt; // assign empty data to datasource for grid
GridView1.DataBind(); // bind the grid shows boom.
Then it should work.
I have a DataGridView (DGV) which is populated using a datatable populated by a Stored Procedure. (All DB calls are correctly returning the requisite data). I then add a combobox column to the DGV which should provide a selection of batchcodes based on the stock code of that row. (Another Stored Procedure Call passing in the StockCode) However, all combo box's on every row are populating with the combined batchcodes for all the rows. In this example I have tried creating an array of datatables to dynamically assign to the DGV.Row but it's the same result. I kind of understand why it isn't working but I don't know how to rectify it. (I am assuming that since I am not specifically defining the cell index of the current combobox and assigning it's datasource to a datatable from the array - it is just overwriting it?? Any help would be greatly appreciated.
// fill the adapter with the executed cmd
adapter.Fill(dt);
//populate the gridview with the datatable
dgv_BOM.DataSource = dt;
dgv_BOM.AutoSize = true;
dgv_BOM.AutoResizeColumns();
dgv_BOM.Columns["StockCode"].DisplayIndex = 0;
dgv_BOM.Columns["Description"].DisplayIndex = 1;
dgv_BOM.RowHeadersVisible = false;
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.HeaderText = "Select Batch Code";
cmb.Name = "cmb";
cmb.Width = 150;
dgv_BOM.Columns.Add(cmb);
DataTable[] dtArray = new DataTable[dgv_BOM.Rows.Count];
int count = 0;
foreach (DataGridViewRow row in dgv_BOM.Rows)
{
if (row.IsNewRow) continue;
stckcd = row.Cells["StockCode"].Value.ToString();
dtArray[count] = SP_RMBatchCodes(stckcd); //returns a datatable object
cmb.DataSource = dtArray[cnt];
cmb.DisplayMember = "BatchNo";
count++;
}
this.dgv_BOM.Columns["Traceable"].Visible = false;
I have an Access database with pictures and other data stored. I want to show the picture from the database in a DatagridView.
This works but the image height is very small in the DatagridView. I also want to stretch the image.
How do I do this ?
Here is where I bind the data from the Access database to the datagridview:
conn.Open();
OleDbCommand cmd = new OleDbCommand(cmdstr, conn);
DataTable table = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(table);
DatagridView1.DataSource = table;
conn.Close();
With this code I created a column to show the picture, but I can't bind the data from the database to this column.
DataGridViewImageColumn photoColumn = new DataGridViewImageColumn();
photoColumn.DataPropertyName = "Photo";
photoColumn.Width = 200;
photoColumn.HeaderText = "Image";
photoColumn.ReadOnly = true;
photoColumn.ImageLayout = DataGridViewImageCellLayout.Normal;
DatagridView1.Columns.Add(photoColumn);
The data of your database are bind by the fist code segment you have written, speciffically:
DatagridView1.DataSource = table;
binds the data brought by your query to your Datagridview. All you have to do is to set up the query accordingly to retrieve the image.
Franlky with Dataadapter I am not quite sure how to store an image but if you use Sqlreader:
...
if (reader.HasRows)
{
while (reader.Read())
{
string s1 = reader[0].ToString(); ///1st field you are interested
string s2 = reader[1].ToString(); //2nd field you want
byte[] img = (byte[])(reader[2]); //your photo image
}
}
Finally be sure, to set on the designer AutogenerateColumns property to true for your Datagrid.
Hello I have a datagridview that already has many, many rows added to it. I also have a textbox that I want to filter the rows out of the datagridview rows if they do not match. I somehow want to connect the textbox to a column to show AND hide the rows. The table was populated using:
public void readExcelFile()
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source = " + Properties.Settings.Default.excelFilePath + "; Extended Properties = \"Excel 8.0;HDR=Yes;IMEX=1\";";
string query = String.Format("select * from [{0}$]", "Batch Export");
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
resultsGrid.DataSource = dataSet.Tables[0];
}
Now when I start typing "John" into the textbox and the first column is "Name", I want all the rows whose Name cell doesn't start with "J", then "Jo", etc. when I delete characters, I want the rows to come back. Is this possible? I've done this before using SQL queries to a DB, but this source is different. And I had to clear the table on every textChanged event. There are about 20k rows here.
Before you assign the Table to the resultGrid.DataSource, you can use DataTable.Select:
var strExpr = "CustomerFirstName = 'John' AND OrderCount > 2";
var strSort = "OrderCount DESC";
// Use the Select method to find all rows matching the filter.
foundRows = ds.Table[0].Select(strExpr, strSort);
Or you can use DataView:
ds.Tables[0].DefaultView.RowFilter = strExpr;
We can used a binding source to filter the data.
private BindingSource dashBoardBindingSource = new BindingSource();
dashBoardBindingSource.DataSource= dataSet.Tables[0];
resultsGrid.DataSource=dashBoardBindingSource;
string filterCriteria = "CustomerFirstName={0}";
dashBoardBindingSource.Filter=string.Format(CultureInfo.CurrentCulture, filterCriteria, textboxName.text);
I have a web part, in the createchildcontrols function it creates a gridview, calls a stored procedure and populates the grid view. One column of the gridView is a command field that has the key value for an item & is passed to another web part on the page to show the details. All was working fine until they wanted me to add a search capability to the list web part.
At first this appeared to work, the data in the columns sems to reflect correct search results, but the command field retains the orginal values when the page was first loaded with no search criteria.
Also, when doing the search it appears that it goes through the createchildcontrols function, populates gridview with all of the items, then runs through the code in the btnSearch_Click where more sql is run with the specific search criteria and the gridview
is re-bound with the search results (but orginal key values in command field).
Any ideas on how I've messed this up?
Code from CreateChildControls:
_view = new GridView();
this.Controls.Add(this._view);
_view.Caption = "Rate Quote Email";
_view.AutoGenerateColumns = true;
_view.DataKeyNames = new string[] { "XREF_ID" };
CommandField field = new CommandField();
_view.SelectedRowStyle.BackColor = Color.Red;
field.ShowSelectButton = true;
field.ButtonType = ButtonType.Link;
_view.Columns.Add(field);
_view.AllowPaging = true;
_view.PageSize = 20;
_view.AlternatingRowStyle.BackColor = Color.Cornsilk;
_view.PageIndexChanging += new GridViewPageEventHandler(_view_PageIndexChanging);
Code from btnSearch_Click:
DataSet ds = new DataSet();
rdr = cmd.ExecuteReader();
ds.Clear();
_view.DataSource = null;
ds.Load(rdr, LoadOption.PreserveChanges, "");
rdr.Close();
rdr.Dispose();
_view.DataSource = ds.Tables[0];
_view.DataBind();
DataSet ds = new DataSet();
ds.Clear();
rdr = cmd.ExecuteReader();
ds.Load(rdr, LoadOption.PreserChanges, "");
rdr.Close();
rdr.Dispose();
_view.DataSource = null;
_view.DataSource = ds.Tables[0];
_view.DataBind();
ds.Dispose();
cmd.Dispose();
conn.Dispose();