I acquired this code from someone and need to organize the list alphabetically. I tried to add an ORDER BY at the end of the Select but it actually makes the whole list empty. I then tried adding additional code to sort it after the list is retrieved, still nothing. Any ideas?
Thanks in advance!
public void FillDropdowns()
{
SPWeb web = site.RootWeb;
string queryText = "SELECT JobTitle1,Department,PracticeArea,Offices from Scope() WHERE \"SCOPE\" = 'People' AND DisplayInDirectory = 'Include'";//,SecondaryOfficeLocationFROM Scope() WHERE \"SCOPE\" = 'People' " + finalquery + " AND DisplayInDirectory = 'Include' ";//,SecondaryOfficeLocation
FullTextSqlQuery query1 = new FullTextSqlQuery(site);
query1.QueryText = queryText;
query1.ResultTypes = ResultType.RelevantResults;
query1.RowLimit = 1000;
ResultTableCollection resultTables = query1.Execute();
DataTable dt = new DataTable();
if (resultTables.Count > 0)
{
ResultTable relevantResults = resultTables[ResultType.RelevantResults];
dt.Load(relevantResults, LoadOption.OverwriteChanges);
}
int j = dt.Rows.Count;
DataView dv = new DataView(dt);
DataSet ds = new DataSet();
ds.Tables.Add(dt);
ddldept.DataSource = dv.ToTable(true, "Department");
ddldept.DataTextField = "Department";
ddldept.DataValueField = "Department";
ddldept.Items.Insert(0, new ListItem("select department", "select department"));
ddldept.DataBind();
ddlpractice.DataSource = dv.ToTable(true, "PracticeArea");
ddlpractice.DataTextField = "PracticeArea";
ddlpractice.DataValueField = "PracticeArea";
ddlpractice.Items.Insert(0, new ListItem("select practiceArea", "select practiceArea"));
ddlpractice.DataBind();
ddltitle.DataSource = dv.ToTable(true, "JobTitle1");
ddltitle.DataTextField = "JobTitle1";
ddltitle.DataValueField = "JobTitle1";
ddltitle.Items.Insert(0, new ListItem("select title", "select title"));
ddltitle.DataBind();
ddlOffice.DataSource = dv.ToTable(true, "Offices");
ddlOffice.DataTextField = "Offices";
ddlOffice.DataValueField = "Offices";
ddlOffice.Items.Insert(0, new ListItem("select offices", "select offices"));
ddlOffice.DataBind();
}
EDIT: Here is where I added the ORDER BY:
string queryText = "SELECT JobTitle1,Department,PracticeArea,Offices from Scope() WHERE \"SCOPE\" = 'People' AND DisplayInDirectory = 'Include' ORDER BY Department ASC";
Here are a few options:
Add the order by within your SQL Statement
Sort the dataview
Example:
DataTable table = dataSet.Tables["TableName"];
DataView view = table.DefaultView;
view.Sort = "Criteria";
Related
I have a database which include my computer's ids,users,old users etc.I fill my dataview perfectly.In my db I have a olduser column and it's look like ;
john;marry;tonny
And my other column "date" looks like ;
02.10.2018;05.09.2017;30.08.2015
So I want to see my datagridview like
PCNAME ID USER OLDUSER PLACE DATE
computer1 1 herry spain
computer1 1 john spain 02.10.2018
computer1 1 marry spain 05.09.2017
computer1 1 tonny spain 30.08.2015
When I write the code below it always give me
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
error
int i = 0;
public void firstdatagrid()
{
DataTable table = new DataTable();
dataGridView1.DataSource = table;
baglantı = new SqlConnection();
baglantı.ConnectionString = "Server=asdas;Database=asdsa;User Id=asdsa;password=asdaassad";
baglantı.Open();
komut = new SqlDataAdapter("SELECT * FROM TABLE WHERE PCID= '" + pcidcmbx.Text + "'", baglantı);
ds = new System.Data.DataSet();
komut.Fill(ds, "TABLE");
dataGridView2.DataSource = ds.Tables[0];
dataGridView2.Columns[0].HeaderText = "PCNAME";
dataGridView2.Columns[1].HeaderText = "ID";
dataGridView2.Columns[2].HeaderText = "USER";
dataGridView2.Columns[3].HeaderText = "OLD USER";
dataGridView2.Columns[4].HeaderText = "PLACE";
dataGridView2.Columns[5].HeaderText = "DATE";
foreach (DataGridViewRow row in dataGridView2.Rows)
{
names += row.Cells[3].Value;
dates += row.Cells[5].Value;
dataGridView2.Rows[0].Cells[3].Value = "";
dataGridView2.Rows[0].Cells[5].Value = "";
}
foreach (var a in names.Split(new char[] { ';' }))
{
MessageBox.Show(a.ToString());
DataRow newRow = table.NewRow();
table.Rows.Add(newRow);
dataGridView2.Rows[i].Cells[3].Value = a.ToString();
i = i + 1;
}
}
First of all you get this message because your values comes from db and when you try to add a new row manually,datagridview doesn't know what is come.
DataTable table = new DataTable();
DataGridView1.DataSource = table;
So try to use it will fix your problem I guess
DataTable dataTable = (DataTable)dataGridView2.DataSource;
DataRow drToAdd = dataTable.NewRow();
drToAdd[3] = a.ToString();
dataTable.Rows.Add(drToAdd);
I`m having a problem displaying some data on a datagrid view. I send data to MySQL on form2 and then its supposed to be displayed in a datagrid view in form1. The datagrid view is updating perfectly but it seems that the datatable is not getting populated with the full information. There are 2 rows of data that should be displayed. I get 2 empty rows in datagrid view.I checked the database and the information is there. Is it my query that isnt right?
What I need are all the rows that have temp_quote.quote_id in the quotes_idquotes column. Can you help me out? Here is the code:
public void RefreshGrid_parts()
{
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["shopmanagerConnectionString1"];
MySqlConnection con = new MySqlConnection(conSettings.ToString());
con.Open();
MySqlCommand cmd = new MySqlCommand("select * from shopmanager.parts where quotes_idquotes = '" + temp_quote.quote_id + "';",con);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.AutoGenerateColumns = false;
dataGridView1.ColumnCount = 6;
dataGridView1.Columns[0].HeaderText = "# Assembly";
dataGridView1.Columns[0].DataPropertyName = "assemblies_assembly_id";
dataGridView1.Columns[1].HeaderText = "# Part";
dataGridView1.Columns[1].DataPropertyName = "part_number";
dataGridView1.Columns[2].HeaderText = "# Item";
dataGridView1.Columns[2].DataPropertyName = "items_items_id";
dataGridView1.Columns[3].HeaderText = "# Description";
dataGridView1.Columns[3].DataPropertyName = "part_description";
dataGridView1.Columns[4].HeaderText = "Drawing Revision";
dataGridView1.Columns[4].DataPropertyName = "drawing_rev";
dataGridView1.Columns[5].HeaderText = "Quantity";
dataGridView1.Columns[5].DataPropertyName = "quantity";
dataGridView1.DataSource = dt;
con.Close();
}
Here is your property example:
(yes its mssql but the logic is the same just change the types, I don't have the mysql lib at hand right know. i guess you'll figure it out.)
SqlClient.SqlCommand comand = new SqlClient.SqlCommand("Select * From ExampleTable Where Colum1 = $1");
comand.Parameters.Add(new SqlClient.SqlParameter("$1", "1234") { DbType = DbType.Int32 });
this will also parse the decimal string into the correct data type (int32)
Try to comment the lines that create the headers to test if your data will appear in the DataGrid. Also put the AutoGenerateColumns to true. If it does, check the DataPropertyName if it's exactly the names of the columns on your query.
public void RefreshGrid_parts()
{
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["shopmanagerConnectionString1"];
MySqlConnection con = new MySqlConnection(conSettings.ToString());
con.Open();
MySqlCommand cmd = new MySqlCommand("select * from shopmanager.parts where quotes_idquotes = '" + temp_quote.quote_id + "';",con);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.AutoGenerateColumns = true;
//dataGridView1.ColumnCount = 6;
//dataGridView1.Columns[0].HeaderText = "# Assembly";
//dataGridView1.Columns[0].DataPropertyName = "assemblies_assembly_id";
//dataGridView1.Columns[1].HeaderText = "# Part";
//dataGridView1.Columns[1].DataPropertyName = "part_number";
//dataGridView1.Columns[2].HeaderText = "# Item";
//dataGridView1.Columns[2].DataPropertyName = "items_items_id";
//dataGridView1.Columns[3].HeaderText = "# Description";
//dataGridView1.Columns[3].DataPropertyName = "part_description";
//dataGridView1.Columns[4].HeaderText = "Drawing Revision";
//dataGridView1.Columns[4].DataPropertyName = "drawing_rev";
//dataGridView1.Columns[5].HeaderText = "Quantity";
//dataGridView1.Columns[5].DataPropertyName = "quantity";
dataGridView1.DataSource = dt;
con.Close();
}
maybe take Rodrigos suggestion and just let the control generate the columns.
if you want to only this six columns just change the query.
public void RefreshGrid_parts()
{
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["shopmanagerConnectionString1"];
MySqlConnection con = new MySqlConnection(conSettings.ToString());
con.Open();
MySqlCommand cmd = new MySqlCommand("select assemblies_assembly_id as '# Assembly', part_number as '# Part', items_items_id as '# Item', part_description as '# Description', drawing_rev as 'Drawing Revision', quantity as 'Quantity' from shopmanager.parts where quotes_idquotes = $1;",con);
cmd.Parameters.Add(new MySqlParameter("$1", temp_quote.quote_id) { DbType = DbType.Int32 });
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dt;
con.Close();
}
I feel like an idiot. The code is good. The problem was that the text color in the datagrid view was white in a white box so I could not see it. Sorry to have bothered you guys with this. 24 hours spent on a non-existing problem! Wow!
I got values from a .csv file and put them into a datagridview, but I'd like to replace some values before to fill my datagridview.
This is the screen of my .csv file:
and this is my code to try to do it:
string FileName = #"C:\mydir\testcsv.csv";
OleDbConnection conn = new OleDbConnection
("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " +
Path.GetDirectoryName(FileName) +
"; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter
("SELECT * FROM " + Path.GetFileName(FileName), conn);
DataSet ds = new DataSet("Temp");
adapter.Fill(ds);
conn.Close();
DataTable dt = ds.Tables[0];
List<HT> matchhtList = new List<HT>();
matchhtList = (from DataRow dr in dt.Rows
select new HT()
{
Home = dr["Home"].ToString(),
Away = dr["Away"].ToString(),
ScoreHome = dr["ScoreHome"].ToString(),
ScoreAway = dr["ScoreAway"].ToString(),
Segno = dr["Segno"].ToString(),
odd1 = dr["odd1"].ToString(),
oddx = dr["oddx"].ToString(),
odd2 = dr["odd2"].ToString()
}).ToList();
StringBuilder mystring = new StringBuilder("matchhtList");
mystring = mystring.Replace("Rosenborg", "Rihanna")
.Replace("Start", "Stop")
.Replace("Brann", "Circus");
dataGridView2.DataSource = mystring;
Please, if my question is not clear, tell me before to put "-1", I'll try to explain better my question. Thank you very much!
you can replace the the text when you build the list
matchhtList = (from DataRow dr in dt.Rows
select new HT()
{
Home = dr["Home"].ToString().Replace("Rosenborg", "Rihanna"),
Away = dr["Away"].ToString().Replace("Start", "Stop").Replace("Brann", "Circus"),
ScoreHome = dr["ScoreHome"].ToString(),
ScoreAway = dr["ScoreAway"].ToString(),
Segno = dr["Segno"].ToString(),
odd1 = dr["odd1"].ToString(),
oddx = dr["oddx"].ToString(),
odd2 = dr["odd2"].ToString()
}).ToList();
dataGridView2.DataSource = matchhtList;
you can manipulate the values in rowdatabound event of gridview
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound(v=vs.110).aspx
And your datasource must be a List or DataTable in above scenario.
dataGridView2.DataSource = mystring;//Wrong
should be
dataGridView2.DataSource = matchList;
I would like to select a specific column from a Dataset once it's been populated (e.g. Column Grades) and put the values into a list
string excelFile = #"C:\Scores.xlsx";
if (File.Exists(excelFile))
{
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+excelFile+";Extended Properties=Excel 12.0;";
var dataAdapter = new OleDbDataAdapter();
var objConn = new OleDbConnection(connString);
//SELECT [Name],[Grade],[Location] ect...
const string query = "SELECT * FROM [TeamScores$]";
var objCmd = new OleDbCommand(query, objConn);
var table = new DataSet();
dataAdapter.SelectCommand = objCmd;
dataAdapter.Fill(table);
//I would like to filter the DataSet to select only [Name] and populate the values into a List<string>
dataGridView1.DataSource = table.Tables[0]; //Will show all results
}
Your variable naming is confusing you.
var table = new DataSet(); // not good at all
A DataSet is not a table. A DataSet contains DataTables.
Try:
DataSet ScoresDataSet = new DataSet();
Then you can use the Select method on the table (something like...):
DataTable ScoresTable = ScoresDataSet.Tables[0];
dataGridView1.DataSource = ScoresTable.Select("Your criteria");
I have now solved the issue I can change "Grade" to which ever column I wish and it'll show the values associated.
DataTable scoresTable = ScoresDataSet.Tables[0];
var result = scoresTable.AsEnumerable()
.Select(r => r.Field<string>("Grade")).Where(r => r != null);
var listOfGrades = result.ToList();
You need adjust this line:
dataGridView1.DataSource = table.Tables[0]; //Will show all results
for example this one:
dataGridView1.DataSource = table.Tables[0].Select("yourField=5")); // you filter the datarows where yourField is 5.
or
dataGridView1.DataSource = table.Tables[0].Select("yourField>5 and yourField<21")); // is another example
Hopefully this can help you :
System.Data.DataSet dsTemp2 = new System.Data.DataSet();
if (dsTemp2.Tables[0].Rows.Count <= 0)
MessageBox.Show("Records not found");
else
{
foreach (DataRow dRow in dsTemp2.Tables[0].Rows)
{
yourtextbox1.Text = dsTemp2.Tables[0].Rows[0][4].ToString();
yourtextbox2.Text = dsTemp2.Tables[0].Rows[0][5].ToString();
yourtextbox3.Text = dsTemp2.Tables[0].Rows[0][7].ToString();
}
}
This value (val1) I'm passing through url (I mean this operation as jobong filter option in checkbox list, filtering by selection index then passing through another page and retrieve through database):
Default Page 3: /WebSite4/Default4.aspx?vaL1=blue,red
This retrieving form page to view in page.
Default Page 2:
public void grid()
{
con.Open();
cmd = new SqlCommand("select * from lady_cloth where color in('" + Request.QueryString["vaL1"] + "')", con);
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
DataSet ds3 = new DataSet();
da1.Fill(ds3);
con.Close();
if (ds3.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds3;
GridView1.DataBind();
}
else
{
}
}
SqlConnection con = new SqlConnection("Data Source=xxxx;Initial Catalog=e_commerce;User ID=sa;Password=xxx");
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Label1.Text = Request.QueryString["Item"];
//Label2.Text = Request.QueryString["Color"];
//grid();
var colourTable = new DataTable();
colourTable.Columns.Add("Value", typeof(string));
var colours = Request.QueryString["vaL1"].Split(',');
for (int i = 0; i < colours.Length; i++)
{
var newRow = colourTable.NewRow();
newRow[0] = colours[i];
colourTable.Rows.Add(newRow);
}
}
string sql = "SELECT * FROM lady_cloth WHERE color IN (SELECT Value FROM #Colours)";
cmd = new SqlCommand(sql, con);
DataSet ds3 = new DataSet();
using (var adapter = new SqlDataAdapter(sql, con))
{
var parameter = new SqlParameter("#Colours", SqlDbType.Structured);
//parameter.Value = colourTable;
parameter.TypeName = "dbo.StringList";
cmd.Parameters.Add(parameter);
con.Open();
adapter.Fill(ds3);
}
if (ds3.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds3;
GridView1.DataBind();
}
else
{
}
}
I think your problem is that you are not separating your items, so your SQL ends up looking like:
select *
from lady_cloth
where color in('blue,red')
Whereas what you would really want is
select *
from lady_cloth
where color in('blue','red')
If you are using SQL Server 2008 or later then I would recommend using table-valued parameters. The first step would be to create your type:
CREATE TYPE dbo.StringList TABLE (Value NVARCHAR(MAX));
I tend to just create generic types that can be easily reused, but this would be your call.
Then in your method you would need to split your values into an array and add them to a datatable:
var colourTable = new DataTable();
colourTable.Columns.Add("Value", typeof(string));
var colours = Request.QueryString["vaL1"].Split(',');
for (int i = 0; i < colours.Length; i++)
{
var newRow = colourTable.NewRow();
newRow[0] = colours[i];
colourTable.Rows.Add(newRow);
}
You can then add this table to your command as a parameter:
string sql = "SELECT * FROM lady_clock WHERE Color IN (SELECT Value FROM #Colours)"
cmd = new SqlCommand(sql, con);
var parameter = new SqlParameter("#Colours", SqlDbType.Structured);
parameter.Value = colourTable;
parameter.TypeName = "dbo.StringList";
cmd.Parameters.Add(parameter);
Finally, You can reduce your code by just initialising the SqlDataAdapter with your SQL and connection:
public void grid()
{
var colourTable = new DataTable();
colourTable.Columns.Add("Value", typeof(string));
var colours = Request.QueryString["vaL1"].Split(',');
for (int i = 0; i < colours.Length; i++)
{
var newRow = colourTable.NewRow();
newRow[0] = colours[i];
colourTable.Rows.Add(newRow);
}
string sql = "SELECT * FROM lady_clock WHERE Color IN (SELECT Value FROM #Colours)"
DataSet ds3 = new DataSet();
using (var adapter = new SqlDataAdapter(sql, con))
{
var parameter = new SqlParameter("#Colours", SqlDbType.Structured);
parameter.Value = colourTable;
parameter.TypeName = "dbo.StringList";
adapter.Parameters.Add(parameter);
con.Open();
da1.Fill(ds3);
}
if (ds3.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds3;
GridView1.DataBind();
}
else
{
}
}