set gridview column width in c# - c#

i want to fix a grdview column width in page load event.
i bounded this gridview from c# and also uses a datasource from c#
i want to set width for "Address" column ,because it has long data.i also want to use auto scroll to this gridview .
here is my code...
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(str);
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("Select DISTINCT FName+ ' ' +MName+ ' ' +LName as Name,"
+ " HomePhone,MobileNo1,"
+ " UPPER(ResAddr1) ++' '+ UPPER(Resaddr2) ++' '+ UPPER(ResAddr3) ++' '+ UPPER(Resaddr4) ++' '+ UPPER(Resaddr5) ++' '+ UPPER(Resaddr6) ++' '+ Pincode ++' '+City as Address,"
+ " g.Category,f.GroupName as 'Group',Seats,"
+ " dbo.CONCATWTOTSHOW(d.MemberId,d.GID,d.CID)As SeatNo,"
+ " AmountExpected,AmountReceived,Discount,AmountPending,b.Remarks as Reference, (d.MemberId)"
+ " from Person_Master a INNER JOIN Member_Master b ON a.PersonId=b.PersonId"
+ " LEFT JOIN Payment_Master c ON b.MemberId = c.MemberId"
+ " INNER JOIN SeatAssign_Master d ON b.MemberId = d.MemberId"
+ " INNER JOIN Year_Master e ON b.Year = e.Id"
+ " INNER JOIN Group_Master f ON d.Gid=f.Gid"
+ " INNER JOIN Category_Master g ON d.Cid=g.Cid "
+ " where b.Year=2 and g.Cid=2 and b.Active=1 and d.Active=1 ", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}

so do it in RowCreated event
GridView1.RowCreated += new GridViewRowEventHandler(GridView1_RowCreated);
void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Width = 200;
// GridView1.Columns[0].HeaderStyle.Width = 100;
}

One way is to create a Grid view RowCreated event and in that event write
e.Row.Cells[1].Width = Unit.Pixel(300);
Where [1] is the column index.

Related

c# search datagridview with numbers [duplicate]

I have a form that when I select a column name from a ComboBox, and type in a text box it filters and displays the searched criteria in the DataGridView. When I search for "Reference" which is an int data type, which is also identity, and primary key. I get the error message :
"Cannot perform 'Like' operation on System.Int32 and System.String."
My code is
DataTable dt;
private void searchForm_Load(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(#"Data Source=|DataDirectory|\LWADataBase.sdf;");
SqlCeDataAdapter sda = new SqlCeDataAdapter("select * from customersTBL", con);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
comboSearch.Items.Add("[Reference]");
comboSearch.Items.Add("[First Name]");
comboSearch.Items.Add("[Surename]");
comboSearch.Items.Add("[Address Line 1]");
comboSearch.Items.Add("[Address Line 2]");
comboSearch.Items.Add("[County]");
comboSearch.Items.Add("[Post Code]");
comboSearch.Items.Add("[Contact Number]");
comboSearch.Items.Add("[Email Address]");
}
private void searchTxt_TextChanged(object sender, EventArgs e)
{
if (comboSearch.SelectedItem == null)
{
searchTxt.ReadOnly = true;
MessageBox.Show("Please select a search criteria");
}
else
{
searchTxt.ReadOnly = false;
DataView dv = new DataView(dt);
dv.RowFilter = "" + comboSearch.Text.Trim() + "like '%" + searchTxt.Text.Trim() + "%'";
dataGridView1.DataSource = dv;
}
}
Convert the number to a string inside the filter:
dv.RowFilter = string.Format("CONVERT({0}, System.String) like '%{1}%'",
comboSearch.Text.Trim(), searchTxt.Text.Trim());
Try this perhaps?
dv.RowFilter = "'%" + comboSearch.Text.Trim() + "%' like '%" + searchTxt.Text.Trim() + "%'";
It may just be a missing quotation, because the query reads as
" 123 like '%123%' "
the code tried to search from gridview (devexpress)..
DataRow[] dr = dt.Select("invoiceId ='" + Convert.ToInt32(gridView1.GetRowCellValue(id, "invoiceId")) + "' AND '%" + Convert.ToDouble(gridView1.GetRowCellValue(id, "Amount_Paid")) + "%' LIKE '%" + Convert.ToDouble(gridView1.GetRowCellValue(id, "Amount")) + "%' ");
if (dr.Length > 0)
{
MessageBox.Show("already paid");
}

In gridview is not displaying the first row

In gridview that am try to displaying the data in the database but it is ignoring the first row from the tabel & taking the rest of row.., plz suggest me what to do..
below is my code.
protected void Page_Load(object sender, EventArgs e)
{
DBLibrary obj = new DBLibrary();
String Parent = (string)Session["parentName"];
String ss = "Select StudentId from Tbl_Parents where parentName='" + Parent + "'";
SqlDataReader dr6 = obj.ExecuteReader(ss);
dr6.Read();
string id = dr6[0].ToString();
string bind = "SELECT AnuFeeMaster.StudentId, Tbl_Student.SName, AnuFeeMaster.Month, AnuFeeMaster.Year, AnuFeeMaster.FeeAmount, " +
" AnuFeeMaster.PaidAmount FROM AnuFeeMaster INNER JOIN Tbl_Student ON AnuFeeMaster.StudentId = Tbl_Student.StudentId where ( AnuFeeMaster.StudentId ='" + id + "')";//and (AnuFeeMaster.ChkDate='" + date.ToString() + "') ";
SqlDataReader dr = obj.ExecuteReader(bind);
dr.Read();
gv1.DataSource = dr;
gv1.DataBind();
}
Remove the dr.Read(); line.
You are passing the reader already advanced with one position.

Selecting a dropdownlist's initial value

I am trying to make the dropdownlist I have already created inside of the edit page of a formview start on the value previously selected from the sql database for the current user.
So far I have the code to populate the drop down list working correctly:
protected void ddlSelect_Init(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ReinstatementCS"].ConnectionString);
SqlCommand myCommand = new SqlCommand("SELECT Prefix, Number, ClassSection, Location, StartTime, EndTime, ClassDay, Prefix + Number + ', Section: ' + CAST(ClassSection AS VarChar) + ', Location: ' + Location + ', Start Time: ' + StartTime + ', End Time: ' + EndTime + ', Days: ' + ClassDay + ', Credits: ' + CAST(ClassCredit AS VarChar) AS PN, Capacity, GPAReqAbove1, GPAReqBelow1, CreditReqAbove30, CreditReqBelow30, ClassCredit, IsTransfer, SLN FROM Classes");
myCommand.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(myCommand);
DataTable dt = new DataTable();
da.Fill(dt);
DropDownList ddlSelect = FVStudentClass.FindControl("ddlSelect") as DropDownList;
ddlSelect.DataSource = dt;
ddlSelect.DataTextField = "PN";
ddlSelect.DataValueField = "SLN";
ddlSelect.DataBind();
con.Close();
}
Where SLN is the unique value for each item in the dropdownlist and PN is the background information for each item in the dropdownlist. I want the item that is highlighted to be the PN that corresponds to what that specific user already has stored in the database. The problem is that when I try to have that value selected I am using:
protected void FVStudentClass_ModeChanging(object sender, FormViewCommandEventArgs e)
{
if (FVStudentClass.CurrentMode != FormViewMode.Edit)
return;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ReinstatementCS"].ConnectionString);
SqlCommand myCommand = new SqlCommand("SELECT Prefix + Number + ', Section: ' + CAST(ClassSection AS VarChar) + ', Location: ' + Location + ', Start Time: ' + StartTime + ', End Time: ' + EndTime + ', Days: ' + ClassDay + ', Credits: ' + CAST(ClassCredit AS VarChar) AS PN, SLN FROM Classes JOIN StudentClass on SLN = SCClass WHERE SCWSUID = " + Request.QueryString["ALWSUID"]);
myCommand.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(myCommand);
DataTable dt = new DataTable();
da.Fill(dt);
DropDownList ddlSelect = new DropDownList();
ddlSelect = FVStudentClass.FindControl("ddlSelect") as DropDownList;
if (ddlSelect != null)
{
ddlSelect.DataSource = dt;
ddlSelect.Items.FindByText(dt.Rows[0]["PN"].ToString()).Selected = true;
}
con.Close();
}
but I'm still stuck because the dropdownlist does not start out with the saved value being selected. Do you know how to fix this? Am I using the wrong command (Should I use something besides ModeChanging)?
Thanks!
Try implementing the logic to select the DropDownList item on the FormView DataBound event, the ModeChanging event happens before the mode is actually changed.
You should be able to just set ddlSelect.SelectedValue to the value you want the dropdown to select.
ddlSelect.SelectedValue = dt.Rows[0]["PN"].ToString();

Automatically Update Values in Database from DataGridView

I'm currently working on a project using MySql in combination with C#.
The Data for the DataGridView is provided by a join from multiple tables in the DB. To show the data I use the following, working, code:
adapter.SelectCommand = new MySqlCommand(
" SELECT" +
" l.lot AS Lot, "+
" m.comment AS Bemerkungen," +
... (multiple columns from different tables) ...
" FROM m " +
" JOIN m2p ON m.m2p_id = m2p.id" +
... (more joins) ...
, this._mySqlConnection);
dataGridView1.DataSource = data;
adapter.Fill(data);
Now the user of the GUI is allowed to modify a certain column (the "comment" column). So I assigned an eventHandler to the CellEndEdit event and when the user modified the allowed column the adapter.Update(data) is called. Now this doesn't perform the correct action.
To define my updatecommand I used the following code:
adapter.UpdateCommand = new MySqlCommand(
" UPDATE m" +
" JOIN l ON m.l_id = l.id" +
" SET m.comment = #comment" +
" WHERE l.lot = #lot"
, this._mySqlConnection);
adapter.UpdateCommand.Parameters.Add("#comment", MySqlDbType.Text, 256, "Bemerkungen");
adapter.UpdateCommand.Parameters.Add("#lot", MySqlDbType.Text, 256, "Lot");
Could you explain me how I fix my code to automatically Update the database?
EDIT:
added further source code:
private MySqlDataAdapter warenlagerMySqlDataAdapter, kundenMySqlDataAdapter;
private DataTable warenlagerData, kundenData;
private DataGridView warenlagerGridView;
private void updateWarenlagerView(object sender, EventArgs e) {
warenlagerMySqlDataAdapter.Update(warenlagerData);
}
private void initialzeFields() {
warenlagerGridView.CellEndEdit += new DataGridViewCellEventHandler(this.updateWarenlagerView);
warenlagerMySqlDataAdapter = new MySqlDataAdapter();
warenlagerData = new DataTable();
}
private void initializeWarenlagerView() {
warenlagerMySqlDataAdapter.SelectCommand = new MySqlCommand(
" SELECT" +
" c.name AS Ursprung, " +
" m2p.art_nr AS ArtNr," +
" m.delivery_date AS Eingangsdatum," +
" CONCAT(FORMAT(m.delivery_amount / 100, 2), 'kg') AS Eingangsmenge, " +
" l.lot AS Lot," +
" m.quality AS Qualität," +
" m.comment AS Bemerkungen," +
" CONCAT(m.units, 'kg') AS Units," +
" CONCAT(FORMAT(s.amount / 100, 2), 'kg') AS Lagermenge, " +
" FORMAT(m.base_price / 100, 2) AS Einkaufspreis," +
" FORMAT(s.amount/10000 * m.base_price, 2) AS Wert" +
" FROM mushrooms AS m " +
" JOIN mushroom2path AS m2p ON m.mushroom2path_id = m2p.id" +
" JOIN countries AS c ON m.origin_id = c.id" +
" JOIN lots AS l ON m.lot_id = l.id" +
" JOIN stock AS s ON s.mushrooms_id = m.id"
, this._mySqlConnection);
warenlagerGridView.DataSource = warenlagerData;
warenlagerMySqlDataAdapter.Fill(warenlagerData);
warenlagerMySqlDataAdapter.UpdateCommand = new MySqlCommand(
" UPDATE mushrooms AS m" +
" JOIN lots AS l ON m.lot_id = l.id" +
" SET m.comment = #comment" +
" WHERE l.lot = #lot"
, this._mySqlConnection);
warenlagerMySqlDataAdapter.UpdateCommand.Parameters.Add("#comment", MySqlDbType.Text, 256, "Bemerkungen");
warenlagerMySqlDataAdapter.UpdateCommand.Parameters.Add("#lot", MySqlDbType.Text, 256, "Lot");
}
This is the whole code concerning this problem. I'm 100% sure the adapter.Update(data) method is called (debugging). And the data which is passed to the adapter.Update() method contains the new data.
Please try this update query it works.
UPDATE mushrooms
SET comment = #comment
WHERE
l_id=(select id from l where lot=#lot)
Your update statement is incorrect. It should be:
"UPDATE m FROM mushrooms m JOIN lots l ON m.lot_id = l.id SET m.comment = #comment WHERE l.lot = #lot"
Did you forget to execute the warenlagerMySqlDataAdapter.UpdateCommand?
You are just setting the command and the parameters but not executing it.
What I see is that you are calling the update when the info is updated, but your update command is not loaded.
You just call updateWarenlagerView when you update the row, but where are you calling initialzeFields?
Or am I missing code?
Try moving your update code from the CellEndEdit event to the CellValueChanged event and see if this works.
Try this example out:
public void UpdateAllFromDgv(DataGridView dataGridView1)
{
string query = "Update List set ColumnName1=#Value1" +
",ColumnName2=#Value2" +
",ColumnName3=#Value3" +
",ColumnName4=#Value4" +
",ColumnName5=#Value5" +
",ColumnName6=#Value6 where ColumnName0=#Value0";
try
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
using (MySqlConnection con = new MySqlConnection(ConnectionString))
{
using (MySqlCommand cmd = new MySqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#Value0", row.Cells[0].Value);
cmd.Parameters.AddWithValue("#Value1", row.Cells[1].Value);
cmd.Parameters.AddWithValue("#Value2", row.Cells[2].Value);
cmd.Parameters.AddWithValue("#Value3", row.Cells[3].Value);
cmd.Parameters.AddWithValue("#Value4", row.Cells[4].Value);
cmd.Parameters.AddWithValue("#Value5", row.Cells[5].Value);
cmd.Parameters.AddWithValue("#Value6", row.Cells[6].Value);
con.Open();
cmd.ExecuteNonQuery();
dataGridView1.ResetBindings();
con.Close();
}
}
}
}
catch (MySqlException MsE)
{
MessageBox.Show(MsE.Message.ToString());
}
}

How can i show multi checkbox on datagridview

i need show multi checkbox on datagridview.
i have 4 checkbox when select 2 checkbox it's show 2 checkbox on datagridview.
Ex 2 checkbox.
CheckBox missShw
0001
0002
CheckBox leaveFull
0003
0004
i'm First select CheckBox missShw and CheckBox leaveFull it's output.
0003
0004
OR
i'm First select CheckBox leaveFull and CheckBox missShw it's output.
0001
0002
i need output when 2 checkbox.
0001
0002
0003
0004
now, i'm select 2 checkbox, so it's show all data to datagridview but it's don't show all data.
This code:
public void missShw()
{
SqlConnection conn = new SqlConnection(appConn);
string sql = "SELECT [filesTA].EmpNo,[Employee].Title + ' ' + [Employee].[First Name] + ' ' + [Employee].[Last Name] as 'FullName',[filesTA].ChkDate"
+ ",Convert(nvarchar(5),[filesTA].ChkIn,108) as 'ChkIn',Convert(nvarchar(5),[filesTA].ChkOut,108) as 'ChkOut"
+ ",[filesTA].LateMin"
+ " From [WebSP].[dbo].[filesTA] inner join [WebSP].[dbo].[Employee] on [Employee].EmployeeNo=[filesTA].EmpNo INNER JOIN [WebSP].[dbo].[CompanyData] On [CompanyData].Company = [Employee].Company"
+ " WHERE [filesTA].ChkDate ='" + dateTimePicker.Value.ToString("yyyy-MM-dd") + "'"
+ " and [Employee].Section = '" + cbSection.SelectedValue + "'"
+ " and [Employee].Team = '" + cbTeam.SelectedValue + "'"
+ " and [filesTA].ErrorCode = '2'";
da = new SqlDataAdapter(sql, Conn);
DataSet ds = new DataSet();
da.Fill(ds);
Conn.Close();
dgvShow.DataSource = ds.Tables[0];
}
public void leaveFull()
{
SqlConnection conn = new SqlConnection(appConn);
string sql = "SELECT [filesTA].EmpNo,[Employee].Title + ' ' + [Employee].[First Name] + ' ' + [Employee].[Last Name] as 'FullName',[filesTA].ChkDate"
+ ",Convert(nvarchar(5),[filesTA].ChkIn,108) as 'ChkIn',Convert(nvarchar(5),[filesTA].ChkOut,108) as 'ChkOut"
+ ",[filesTA].LateMin"
+ " From [WebSP].[dbo].[filesTA] inner join [WebSP].[dbo].[Employee] on [Employee].EmployeeNo=[filesTA].EmpNo INNER JOIN [WebSP].[dbo].[CompanyData] On [CompanyData].Company = [Employee].Company"
+ " WHERE [filesTA].ChkDate ='" + dateTimePicker.Value.ToString("yyyy-MM-dd") + "'"
+ " and [Employee].Section = '" + cbSection.SelectedValue + "'"
+ " and [Employee].Team = '" + cbTeam.SelectedValue + "'"
+ " and [filesTA].ErrorCode = '3'";
da = new SqlDataAdapter(sql, Conn);
DataSet ds = new DataSet();
da.Fill(ds);
Conn.Close();
dgvShow.DataSource = ds.Tables[0];
}
//missShw()
private void checkBox4_CheckedChanged(object sender, EventArgs e)
{
if (checkBox4.Checked == true)
{
missShw();
}
}
//leaveFull()
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
if (checkBox3.Checked == true)
{
leaveFull();
}
}
Thanks for your time. :)

Categories

Resources