I was trying to change the font size on specific row cell depends on what length the string is by using DataRow, using DataGridView I get an error, same with the DataGrid. How can I manipulate the cell in every row using DataRow?
DataTable dt = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter("Command Here"))
{
da.Fill(dt);
foreach (DataRow asd in dt.Rows)
{
if (asd[4].ToString().Length >= 45)
{
asd[4] = "test";
}
}
}
I know using = is setting a new value for that column cell, but I was trying to manipulate its style.
Related
i would like to request you that kindly help me how to pass the value from Xamarin DataGridView selected row to another page TextBox. please see the mention below of my code.
This is my code to fill the DatGridView:
private void Bind_GVhkCL(string text)
{
{
string query = "SELECT Room_No as 'Room No',Room_Status as 'Room Status', S_Time as 'Start Time',E_Time as 'End Time',c_date as 'Create Date'from HK_Chk " + text;
sqlConnection.Open();
SqlDataAdapter da = new SqlDataAdapter(query, sqlConnection);
DataTable dt = new DataTable();
da.Fill(dt);
GVhkCL.ItemsSource = dt;
//GVhkCL.RowHeight = 60;
sqlConnection.Close();
}
}
This is code that I am trying to pass the value to another form or you can give me any other idea:
private void DataGridView_DoubleTap(object sender, DataGridGestureEventArgs e)
{
if (e.Item != null)
{
var editForm = new EditFormPage(GVhkCL, GVhkCL.GetItem(e.RowHandle),
(DataTemplate)Resources["Room No"]);
Navigation.PushAsync(editForm);
}
}
I have a DropDownList which gets it values from SQL table
I want to get the Average of the selected item (course in this case) from the dropDownList and to show it in a label :
This section works -
SqlConnection sqlConnection1;
sqlConnection1 = new SqlConnection(#"Data Source=HA\SQLEXPRESS; Initial Catalog=Grades1; Integrated Security=True");
SqlCommand Command = null;
Command = new SqlCommand("SELECT Course FROM GradesTable1", sqlConnection1);
Command.Connection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(Command);
DataTable dataTble1 = new DataTable();
dataAdapter.Fill(dataTble1);
if (dataTble1.Rows.Count > 0)
{
foreach (DataRow row in dataTble1.Rows)
{
ListItem course1 = new ListItem(row["Course"].ToString());
if (!DropDownList1.Items.Contains(course1))
{
DropDownList1.Items.Add(course1); // showing the 2 courses
}
}
}
Command.Connection.Close();
}
}
Here is the problem - (I get nothing, no data )
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection sqlConnection1;
sqlConnection1 = new SqlConnection(#"Data Source=HA\SQLEXPRESS; Initial Catalog=Grades1; Integrated Security=True");
SqlCommand Command = null;
Command = new SqlCommand($"SELECT AVG(Grade) FROM GradesTable1 WHERE Course = #course", sqlConnection1);
Command.Parameters.AddWithValue("#course", DropDownList1.SelectedItem);
Command.Connection.Open();
SqlDataReader sqlDataReader1 = Command.ExecuteReader();
if (sqlDataReader1.Read())
{
LabelAverage.Text = sqlDataReader1[0].ToString();
}
else
{
LabelAverage.Text = "No Data"; // doesn't get into here anyhow
}
}
EDIT
I tried several variations as $"SELECT AVG(Grade) AS "ClassAVG" FROM GradesTable1 WHERE Course = #course" and Command.Parameters.AddWithValue("#course", DropDownList1.SelectedItem.Text), or DropDownList1.SelectedValue
I believe the problem is with the DropDownlist values which being received from the SQL and are not hard coded.
Is there a correct way to this? is it possible without knowing what are the "Courses" in advanced?
Thanks for the answers, feel free to give your opinion.
I found out what was missing in the DropDownList in aspx page (not the aspx.cs page) -the AutoPostBack="true"
Adding that to DropDownList solved the problem.
// query = Sql query
query.Select(s => new MusteriNoktaComboItemDTO
{
Label = s.Adi,
Value = s.ID.ToString()
}).ToList();
I am having some difficult manually sorting data on a gridview. I used a dataset and when set the AllowSort to true and also wrote the code to handle the sort based on the guide given on https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx . However, when I run my code, the data displays but when I click the header of each column, nothing happens.
here is my code
protected void Page_Load(object sender, EventArgs e)
{
string connstring = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "SELECT Count(Student.StudentID) AS StdCount, Schools.Name, Schools.StartDate, School.SchoolFees FROM Schools INNER JOIN Students ON Schools.SchoolID = Student.SchoolID WHERE School.Active = 1 GROUP BY Schools.Name, Schools.StartDate, Schools.SchoolFess ORDER BY Schools.Name ASC";
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables.Count > 0)
{
DataTable dt = ds.Tables[0];
ViewState["datable"] = dt;
}
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)ViewState["datable"];
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
GridView1.DataSource = ViewState["datable"];
GridView1.DataBind();
}
}
private string GetSortDirection(string column)
{
// By default, set the sort direction to ascending.
string sortDirection = "ASC";
// Retrieve the last column that was sorted.
string sortExpression = ViewState["SortExpression"] as string;
if (sortExpression != null)
{
// Check if the same column is being sorted.
// Otherwise, the default value can be returned.
if (sortExpression == column)
{
string lastDirection = ViewState["SortDirection"] as string;
if ((lastDirection != null) && (lastDirection == "ASC"))
{
sortDirection = "DESC";
}
}
}
// Save new values in ViewState.
ViewState["SortDirection"] = sortDirection;
ViewState["SortExpression"] = column;
return sortDirection;
}
Any help will be appreciated. Thanks
You need to bind the DefaultView of the DataTable, which is this orderly, not ViewState variable.
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)ViewState["datable"];
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
GridView1.DataSource = dt.DefaultView;
GridView1.DataBind();
}
}
This looks to be a Page LifeCycle issue.
Every time you post back the entire Page LifeCycle runs
In your case you are retrieving and overwriting ViewState["datable"] on every postback, assuming of course that if (ds.Tables.Count > 0) evaluates to true.
And then you do this in Page Load:
GridView1.DataSource = ds;
but in your sorting routine you access:
DataTable dt = (DataTable)ViewState["datable"];
...
GridView1.DataSource = ViewState["datable"];
You just replaced GridView.DataSource, which initially was a DataSet, with a DataTable
Wrap your initial data Retrieval in PageLoad like this
if( !Page.IsPostback )
{
// This retrieves Data once, and you persist it
// in the ViewState no need to Keep retrieving it
// unless the data has changed
}
// Rebind outside the if
GridView1.DataSource = (DataTable) ViewState["datable"];
GridView1.DataBind();
Addendum
Per Andrei he is correct. ViewState is a hidden field on your rendered ASPX. View the page source in your browser and search for
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="" />
It's Ok to use as a learning aid as long as the dataset is small and doesn't contain any confidential information.
But as it's transmitted to and from your page on every postback you incur a lot of overhead. Imagine if your DataSet contained several thousand rows.
Session State is a better option, but the Application Cache is better still. Server Data Controls like SqlDataSource make use of this cache and so can you. Access it just like ViewState:
ViewState["datable"] = dt;
Cache["datable"] = dt;
But don't go crazy with it. ViewState, SessionState, Cookies, LocalStorage, etc all have their place, learn them.
I'm trying to update a SQLite database with a column "URL" with a specific value. The old url format is "http://www.blz.nl/voster/boek/9789056628512" and the new one is "http://www.blz.nl/voster/boekwinkel/zoeken/?q=9780789327505&oa=true&searchin=taal&taal=dut".
What I am trying to do is replace the url to the new format but keep the value of the 'Q' param from the old url. What is the fastest / best way to achieve this for all columns? I have no idea how to approach this using an SQL query.
You want the SQL?
Basically, you read in the table, search for your keyword, replace it, and write that data back to the database.
Assuming your database name is "mydatabase.db", your code would look something like this (untested):
using Devart.Data.SQLite;
public void Convert()
{
using (var conn = new SQLiteConnection("DataSource=mydatabase.db"))
{
var boek = "//boek//";
var boekwinkel = "//boekwinkel//";
var boek_len = boek.Length;
var table = new DataTable();
var sqlCmd = "SELECT * FROM TableName1;";
conn.Open();
// Read the data into the DataTable:
using (var cmd = new SQLiteCommand(sqlCmd, conn))
{
// The DataTable is ReadOnly!
table.Load(cmd.ExecuteReader());
}
// Use a new SQLiteCommand to write the data.
using (var cmd = new SQLiteCommand("UPDATE TableName1 SET URL=#NEW_URL WHERE URL=#URL;", conn))
{
cmd.Parameters.Add("#URL", SQLiteType.Text, 20);
cmd.Parameters.Add("#NEW_URL", SQLiteType.Text, 20);
foreach (DataRow row in table.Rows)
{
var url = String.Format("{0}", row["URL"]).Trim();
cmd.Parameters["#URL"].SQLiteValue = row["URL"];
if (!String.IsNullOrEmpty(url))
{
var index = url.IndexOf(boek);
if (-1 < index)
{
var first = url.Substring(0, index);
var middle = boekwinkel;
var last = url.Substring(index + boek_len);
var new_url = String.Format("{0}{1}{2}&oa=true&searchin=taal&taal=dut", first, middle, last);
// Place a break point after String.Format.
// Make sure the information being written is correct.
cmd.Parameters["#NEW_URL"].SQLiteValue = new_url;
cmd.ExecuteNonQuery();
}
}
}
}
conn.Close();
}
}
I have this methode to loop through if the data in my gridview is checked or not, if they are checked they should be inserted into the database.
As you can see the only data I want to insert from the gridview is the text from cell[2] in the gridview and it's in the name of #HeaderName
using (SqlConnection con = new SqlConnection("my con string"))
{
con.Open();
foreach (GridViewRow row in GridViewConsNames.Rows)
{
CheckBox myCheckBox = row.FindControl("myCheckBox") as CheckBox;
if (myCheckBox.Checked)
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Accounting_Consolidation_ServiceOutputs(Cusomer_Name, Service_Name, Header_Name, Sort_Postion, Rename_to, Value) Values(#CustName,#ServiceName,#HeaderName,#Sort,#Rename,#Value)", con))
{
//cmd.Parameters.AddWithValue("PersonId", Convert.ToInt32(GridViewConsNames.DataKeys[row.RowIndex].Value));
cmd.Parameters.AddWithValue("#CustName", TextBoxCustName.Text);
cmd.Parameters.AddWithValue("#ServiceName", DropDownListServicesAvailable2.SelectedItem.Text);
cmd.Parameters.AddWithValue("#HeaderName", "Name of the checked cells from my gridview");
cmd.Parameters.AddWithValue("#Sort", null);
cmd.Parameters.AddWithValue("#Rename", "");
cmd.Parameters.AddWithValue("#Value", null);
cmd.ExecuteNonQuery();
}
}
}
}
I have tried with this
GridViewRow row = GridViewConsNames.SelectedRow;
string headername = row.Cells[2].Text;
But this seems not working
Why do you use GridViewRow row = GridViewConsNames.SelectedRow when you actually want to use all rows where the checkbox is selected?
So i guess that this is what you want:
foreach (GridViewRow row in GridViewConsNames.Rows)
{
CheckBox myCheckBox = row.FindControl("myCheckBox") as CheckBox;
if (myCheckBox.Checked)
{
// ...
string headerName = row.Cells[2].Text;
cmd.Parameters.AddWithValue("#HeaderName", headerName);
// ...
}
}