DataGridView and SQL query name - c#

I have a function that gets all the data from database (also the column names) and shows it in a DataGridView.
The problem is that the DataGrid show also the column name. How can I edit the columns name? I already tried
dataGridView1.Columns[0].Name = "xxx";
without success.
private void PriceChange_Load(object sender, EventArgs e)
{
DbCards d = new DbCards();
dataGridView1.DataSource = d.GetAllcards().Tables[0];
}
GetAllcards() is select * from Cards.

If you want to change the header text displayed by a DataGridViewColumn you need to use the HeaderText property
dataGridView1.Columns[0].HeaderText = "xxx";

Set dataGridView1.Columns[0].HeaderText instead

Related

C# My BindingSource filter won't seems to update dataGrid

I've tried updating dynamically my datasource on my datagrid, but it keeps returning no value... Note : i've already closed my connection to my SQL database and am tried to filter it through a textbox textchanged method (at each change, it would dynamically filter the Binding).
It seems my textbox and everything is populated at each step i've checked each propert, and yes, my column to be filtered is verb
void txtChanged(object sender, EventArgs e)
{
TextBox tbTemp = (TextBox)sender;
DataTable dt = new DataTable();
dataSet.dataAdapter.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
bs.Filter = string.Format("[{0}] LIKE '%{1}%'", "Verb", tbTemp.Text);
dataGrid.DataSource = bs;
}
}
Thanks in advance for the help!
Oh my god, guys. it works like a charm now! Thanks for the help, i would like to help any other people with this issue. It was sooooo complex... Your solution guided me towards the truth :
BindingSource datamember property needs to be set to table. Here is my correct code :
void txtChanged(object sender, EventArgs e)
{
TextBox tbTemp = (TextBox)sender;
dataSet.bdSource.Filter = string.Format("[{0}] LIKE '%{1}%'",
strTemp[Int16.Parse(tb.Name)], tbTemp.Text);
//Use table name instead of verb
dataSet.bdSource.DataMember = "Verbe";
dataGrid.DataSource = null;
dataGrid.DataSource = dataSet.bdSource;
dataGrid.Refresh();
}

Using C# to set System.Drawing.Color.FromName

Objective: The objective is to set the System.Drawing.Color dynamically based on a text value within a datatable. The text value is the name of a color within System.Drawing.Color. The purpose is to change the backcolor of a grid based on the given value.
Issue: The method I am using now does not obtain a value from the datatable and sets the Color to 0,0,0,0. The datatable is created using a ViewState. The research I've conducted on this issue indicates this should work. However, the value obtained from the DataTable is "" . What is incorrect in this code? Thank you in advance for you comments, suggestions and consideration. The code is as follows:
DataTable code
private void CreateList()
{
DataTable dtMyList = new DataTable();
DataColumn dcID = new DataColumn("ID");
dtMyList.Columns.Add(dcID);
DataColumn dcColor = new DataColumn("Color");
dtMyList.Columns.Add(dcColor);
ViewState["MyList"] = dtMyList;
}
On RowDataBound code intended to change the backcolor
protected void grdMyList_RowDataBound(object sender, GridViewEventsArgs e)
{
DataTable dtMyList = (DataTable)ViewState["MyList"];
for (int i = 0; i < dtMyList.Rows.Count; i++)
{
e.Row.Cells[0].BackColor = System.Drawing.Color.FromName(Convert.ToString(dtMyList.Rows[0]["Color"]));
}
}
First of all: Is the datatable filled with any data?
Second: you are trying to fill that one row (given in the event args) with all the colors from the datatable, resulting in that only one property (e.Row.Cells[0].BackColor) is filled with the color coming from the last row in the table (dtMyList.Rows[i]["Color"]).
I think you should first lookup the correct datarow which is attached to your gridrow (e.Row.DataItem), then read its color and then fill the property of your gridrow. Like this:
protected void grdMyList_RowDataBound(object sender, GridViewEventsArgs e)
{
DataRow row = (DataRow)e.Row.DataItem;
e.Row.Cells[0].BackColor = System.Drawing.Color.FromName(row["Color"].ToString());
}
You're looping through the entire table and setting the color for each row. I think you want something like
protected void grdMyList_RowDataBound(object sender, GridViewEventsArgs e)
{
DataTable dtMyList = (DataTable)ViewState["MyList"];
index i = e.Row.RowIndex;
e.Row.Cells[0].BackColor = System.Drawing.Color.FromName(Convert.ToString(dtMyList.Rows[i]["Color"]));
}

Getting specific properties from a list

i am facing a problem
i have a class
public class StudentDetails
{
int S_Detail_ID;
string address;
string email;
}
containg get set method and iam calling a function which is collecting the List<StudentDetails> and showing it in datagridview the problem is that list is returning all properties of the class, but i only want address and email not s_detail_id
here is code for the function
private void btnAddNewRowInGrid_Click(object sender, EventArgs e)
{
List<StudentDetails> lstStudentDetails = GetStudentDetails();
lststudentDetails.Add(new StudentDetails()); //what to do here, studentDetails is returning all properties but i want only addres and email
dataGridView1.DataSource = lstStudentDetails;
}
and GetStudent jusst count rows in datagridview and add a new row
private List<StudentDetails> GetStudentDetails()
{
lstStudentDetails = new List<StudentDetails>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
lstStudentDetails.Add(row.DataBoundItem as StudentDetails);
}
return lstStudentDetails;
}
Select DataGridView in designer and click on little triangle at top right corner of control
Click Edit Columns menu item
Manually add columns for address and email properties (type in property name in DataPropertyName item of column properties)
Disable columns auto-generation
You cannot turn off columns auto-generation from designer - its possible only from code:
dataGridView1.AutoGenerateColumns = false;
After that your code will work.
You can Try hiding the column you do not need by setting its visibility to false.
dataGridView1.Columns["S_Detail_ID"].Visible = false;

C# DataGridView: Value disappearing in dynamic added column

I am coming across something strange or maybe it is the way it works and its just my lack of understand of how the datagridview works. I am dynamically adding a column when I click on a button
private void btnAssign_Click(object sender, EventArgs e)
{
if (!gvData.Columns.Contains("DepartmentId"))
{
DataGridViewTextBoxCell cell = new DataGridViewTextBoxCell();
DataGridViewColumn dc = new DataGridViewColumn();
dc = new DataGridViewTextBoxColumn();
dc.HeaderText = "DepartmentId";
dc.Name = "DepartmentId";
dc.CellTemplate = cell;
gvData.Columns.Add(dc);
}
foreach(DataGridViewRow row in gvData.SelectedRows)
{
row.Cells["DepartmentId"].Value = getSelectedValues(clbDept);
}
}
first it checks if the DepartmentId column is in the datagridview (dgv). If not then I create a new Datagridviewtextboxcolumn and sets the appropriate settings. Then adds values to the cells. SO far so good... this where is does weird things... when I sort another column, the data in the 'DepartmentId' column disappears. Data disappears in the columns that I dynamically create. Do i have to use a save method or something?
Instead of adding data directly to datagridview you need to add column to datasource and reassign the datasource to datagridview. This will resolve your sorting issue.

How to Set a gridview column width when binding to a datatable

I am binding a table to a gridview in asp.net as such
grdIssues.DataSource = mdtIssues;
grdIssues.DataBind();
The problem is I cannot then control the column width, asp.net seems to decided on it's own what width each column should be. Methods such as
grdIssues.Columns[0].ItemStyle.Width = 100;
grdIssues.Columns[1].ItemStyle.Width = 100;
don't work because the columns are created dynamically. I cannot believe there isn't a way to do this short of manually creating each column and filling each row.
You dont have to manually create the columns to set them the width, you can do this
foreach (DataControlField column in OrdersGV.Columns)
{
column.ItemStyle.Width = Unit.Pixel(100);
}
I was able to change the width of a certain Gridview column (bound to a Datatable) with the RowDataBound event:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
e.Row.Cells[0].Attributes["width"] = "200px";
}
I like to answer my own question whenever I can so future users searching the thread will find the answer.
I could not find a way to do what I wanted directly. However I found if I define the columns myself, I could change the properties. In this example, I wanted to center the column data. Something like this.
BoundField bdfRaisedDate = new BoundField();
clsUtilities.SetBoundFieldCenter(ref bdfRaisedDate, "RaisedDateShort", "Opened", "RaisedDate");
grdIssues.Columns.Add(bdfRaisedDate);
grdIssues.DataSource = mdtIssues;
grdIssues.DataBind();
public static void SetBoundFieldCenter(ref BoundField bdfAny, string pDataField, string pHeadingValue, string pSortExpression)
{
bdfAny.DataField = pDataField;
bdfAny.HeaderText = pHeadingValue;
bdfAny.SortExpression = pSortExpression;
bdfAny.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
bdfAny.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
}
I did it as:
gridView1.HeaderRow.Cells[0].Attributes["Width"] = "100px";
gridView1.HeaderRow.Cells[1].Attributes["Width"] = "50px";
gridView1.HeaderRow.Cells[2].Attributes["Width"] = "200px";
I'd do it like this:
foreach (DataControlField field in grdIssues.Columns)
{
field.HeaderStyle.Width = 100;
}

Categories