I am trying to show a dynamic barchart from database in winform application but it is not coming and giving me Argument out of Exception error at var p2 = series.Points[arrlocationSTD]; when arrlocationSTD=1. Here is my code in c#..
void LoadBarChart(string qurystring)
{
if (calltype.Equals("TRANSFERED"))
{
totalTransfered = dr["SummaryOfCalls"].ToString();
intTRANSFERED = int.Parse(totalTransfered, CultureInfo.InvariantCulture);
if (i == 0)
{
arrlocationTransferred = i;
series.Points.Add(intTRANSFERED);
var p7 = series.Points[arrlocationTransferred];
p7.Color = Color.Yellow;
p7.AxisLabel = "TRANSFERED";
p7.LegendText = "TRANSFERED";
p7.Label = totalTransfered;
i++;
}
else
{
arrlocationTransferred = i;
series.Points.Add(intTRANSFERED);
var p7 = series.Points[arrlocationTransferred];
p7.Color = Color.Yellow;
p7.AxisLabel = "TRANSFERED";
p7.LegendText = "TRANSFERED";
p7.Label = totalTransfered;
}
}
}
barChart.Invalidate();
pnlBar.Controls.Add(barChart);
}
Please help me to resolve this.
Thanks in advance..
You'll need to add your additional processing, but the following might help.
I'd strongly recommend that you get the chart showing your data correctly before you start changing colour properties and such.
void LoadBarChart(string qurystring)
{
String conn = Strings.ConnectionString; // You fill this in.
Dictionary<String,int> callSummariesByTypeOfCall =
new Dictionary<String,int>();
MySqlConnection con = new MySqlConnection(conn);
MySqlCommand comm = new MySqlCommand(qurystring, con);
con.Open();
MySqlDataReader dr = comm.ExecuteReader();
// Get the data into a dictionary
while (dr.Read())
{
String calltype = dr["TypeOfCall"].ToString();
int summary = int.Parse(dr["Calls"].ToString(), CultureInfo.InvariantCulture);
callSummariesByTypeOfCall[calltype] = summary;
}
// Do any other processing you need here
// Bind the data onto the Series
Series series = new Series
{
Name = "series2",
IsVisibleInLegend = false,
ChartType = SeriesChartType.Column
};
series.Points.DataBindXY(
callSummariesByTypeOfCall.Keys,
callSummariesByTypeOfCall.Values);
barChart.Series.Add(series);
barChart.Invalidate();
pnlBar.Controls.Add(barChart);
}
Related
I have two list (1st with values from a website, 2nd with values from a .csv file) and I'd like to join them in another list, starting two equals values, and display it in a datagridview.
Before to post the code, I'd like to say that I tried to fill my datagridview with these two lists separately and they work.
I didn't get any error, but I can't see my datagridview with values.
I'm going to post my code and explain it.
First List Code:
var url = textBox5.Text;
//var url = "http://www.betexplorer.com/soccer/norway/tippeligaen/results/";
var web = new HtmlWeb();
var doc = web.Load(url);
Bets = new List<Bet>();
// Lettura delle righe
var Rows = doc.DocumentNode.SelectNodes("//tr");
foreach (var row in Rows)
{
if (!row.GetAttributeValue("class", "").Contains("rtitle"))
{
if (string.IsNullOrEmpty(row.InnerText))
continue;
var rowBet = new Bet();
foreach (var node in row.ChildNodes)
{
var data_odd = node.GetAttributeValue("data-odd", "");
if (string.IsNullOrEmpty(data_odd))
{
if (node.GetAttributeValue("class", "").Contains("first-cell"))
{
rowBet.Match = node.InnerText.Trim();
var matchTeam = rowBet.Match.Split(new[] { " - " }, StringSplitOptions.RemoveEmptyEntries);
rowBet.Home = matchTeam[0];
rowBet.Host = matchTeam[1];
}
if (node.GetAttributeValue("class", "").Contains("result"))
{
rowBet.Result = node.InnerText.Trim();
var matchPoints = rowBet.Result.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
int help;
if (int.TryParse(matchPoints[0], out help))
{
rowBet.HomePoints = help;
}
if (matchPoints.Length == 2 && int.TryParse(matchPoints[1], out help))
{
rowBet.HostPoints = help;
}
}
if (node.GetAttributeValue("class", "").Contains("last-cell"))
rowBet.Date = node.InnerText.Trim();
}
else
{
rowBet.Odds.Add(data_odd);
}
}
if (!string.IsNullOrEmpty(rowBet.Match))
Bets.Add(rowBet);
}
}
Second List & Combined List Code:
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 = new DataTable();
DataTable dt = ds.Tables[0];
//dataGridView2.DataSource = dt;
// dataGridView2.DataMember = "Table";
List<HT> matchlist = new List<HT>();
matchlist = (from DataRow dr in dt.Rows
select new HT()
{
Home = dr["Home"].ToString().Replace("Milan", "AC Milan").Replace("Roma", "AS Roma"),
Host = dr["Host"].ToString().Replace("Milan", "AC Milan").Replace("Roma", "AS Roma"),
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 = matchlist;
var combinedDataList = (from d1 in Bets
//join d2 in dataList2 on d1.Home equals d2.Home
join d2 in matchlist on new { d1.Home, d1.Host } equals new { d2.Home, d2.Host }
select new CombinedData
{
Data = d1.Date,
Home = d1.Home,
Away = d1.Host,
HSFT = d1.HomePoints,
ASFT = d1.HostPoints,
HSHT = d2.ScoreHome,
ASHT = d2.ScoreAway,
HODD = d1.odd1,
XODD = d1.oddX,
AODD = d1.odd2,
RisFin = d1.RisFin,
Over05SH = d1.over05sh,
Over05FT = d1.Over05FT,
Over15FT = d1.Over15FT,
Over25FT = d1.Over25FT,
Over35FT = d1.Over35FT,
Over45FT = d1.Over45FT
}).OrderBy(p => p.HODD);
dataGridView2.DataSource = combinedDataList;
Thank you for your attention. Have a fantastic sunday!
EDIT: I delete unnecessary code
EDIT2: I add the screen of my single list output. Let's see:
First List:
Second List:
So, I'd like to merge "ScoreHome" and "ScoreAway" from the second list in my first list based on "Home" and "Host" that I have in both lists.
I have to create a Copy of a Database on SQL Server.
On this way I got a connection to the new DB
ADODB.Connection connection = new ADODB.Connection();
OleDbConnectionStringBuilder builder = new System.Data.OleDb.OleDbConnectionStringBuilder();
builder["Provider"] = provider;
builder["Server"] = #"Themis\DEV";
builder["Database"] = file_name;
builder["Integrated Security"] = "SSPI";
string connection_string = builder.ConnectionString;
connection.Open(connection_string, null, null, 0);
return connection;
}
I create the tables with ADOX
ADOX.Catalog cat, Dictionary<string, ADOX.DataTypeEnum> columntype)
{
List<string> primaryKeysList = GetPrimaryKey(tabelle);
Key priKey = new Key();
Catalog catIn = new Catalog();
catIn.ActiveConnection = dbInfo.ConIn;
Dictionary<string, List<string>> indexinfo = new Dictionary<string, List<string>>();
GetSecondaryIndex(tabelle, indexinfo);
if (columntype.Count != 0) columntype.Clear();
if (size.Count != 0) size.Clear();
foreach (DataRow myField in schemaTable.Rows)
{
String columnNameValue = myField[columnName].ToString(); //SpaltenName
bool ich_darf_dbnull_sein = (bool)myField["AllowDBNull"];
ADOX.Column columne = new ADOX.Column();
columne.ParentCatalog = cat;
columne.Name = columnNameValue;
if (!columntype.ContainsKey(columnNameValue))
{
columntype.Add(columnNameValue, (ADOX.DataTypeEnum)myField["ProviderType"]);
}
columne.Type = (ADOX.DataTypeEnum)myField["ProviderType"];
//type.Add((ADODB.DataTypeEnum)myField["ProviderType"]);
columne.DefinedSize = (int)myField["ColumnSize"];
dbInfo.ColumnName = columnNameValue;
dbInfo.TableName = tabelle;
dbInfo.Column_size = (int)myField["ColumnSize"];
dbInfo.Column_Type = (ADOX.DataTypeEnum)myField["ProviderType"];
size.Add((int)myField["ColumnSize"]);
if (primaryKeysList.Contains(columnNameValue))
{
dbInfo.IsPrimary = true;
}
else dbInfo.IsPrimary = false;
object index = catIn.Tables[tabelle].Columns[columnNameValue].Attributes;
if (index.Equals(ColumnAttributesEnum.adColFixed) || (int)index == 3)
dbInfo.Fixed_length = true;
else
dbInfo.Fixed_length = false;
Console.WriteLine("{0}={1}", myField[columnName].ToString(), catIn.Tables[tabelle].Columns[columnNameValue].Attributes);
TargetDBMS.SetColumnProperties(columne, dbInfo);
switch (columne.Type)
{
case ADOX.DataTypeEnum.adChar:
case ADOX.DataTypeEnum.adWChar:
case ADOX.DataTypeEnum.adVarChar:
case ADOX.DataTypeEnum.adVarWChar:
columne.DefinedSize = (int)myField["ColumnSize"];
break;
default:
break;
}
if (primaryKeysList.Contains(columnNameValue))
{
priKey.Name = "PK_" + tabelle + "_" + columnNameValue;
primaryKeysList.Remove(columnNameValue);
priKey.Columns.Append(myField[columnName], (ADOX.DataTypeEnum)myField["ProviderType"], (int)myField["ColumnSize"]);
}
columnNameList.Add(columnNameValue);
table.Columns.Append(columne);
}
table.Keys.Append((object)priKey, KeyTypeEnum.adKeyPrimary);
}
But when I set the Properties for the columns I got an Exception
internal override void SetColumnProperties(ADOX.Column columne, DbInfo dbInfo)
{
GetColumnProperties(dbInfo);
columne.Properties["Autoincrement"].Value = dbInfo.Field_prop["Autoincrement"];
columne.Properties["Default"].Value = dbInfo.Field_prop["Default"];
columne.Properties["Nullable"].Value = dbInfo.Field_prop["Nullable"];
}
My Program works well for Access DB, but I cannot set it for the DB on SQL Server
Exception (0x80040E21) Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.
If I try this way
string query = "SELECT * FROM Forms";
DataTable dt = new DataTable();
using (SqlConnection sqlConn = Connection())
using (SqlCommand cmd = new SqlCommand(query, sqlConn))
{
sqlConn.Open();
dt.Load(cmd.ExecuteReader());
}
foreach (DataColumn col in dt.Columns)
{
Console.WriteLine(col.ColumnName);
col.AllowDBNull = true;
dt.AcceptChanges();
col.AutoIncrement = false;
dt.AcceptChanges();
}
it does not change the properties in the DB
The Problem is partially solved
columne.Properties["Autoincrement"].Value = (bool)dbInfo.Autoincrement;
because the dbInfo.Autoincrement was an object I have to write (bool) dbInfo.Autoincrement
Not solved is this
columne.Properties["Default"].Value = (string)dbInfo.Default_Value;
because the type of a value Default_Value can be 0, empty ("") or "-"...I don’t know what i can do in this case
So to try and give you an idea of what im working with, I have two drop down boxes. The first drop down box has a list of 4 Applications. The second drop down box changes dynamically with my selection in the first drop down box. I have a chart for each selection in the second drop down box. I have 16 charts total. Each time i change the second selection, the chart changes so that there is only one chart showing at a time. Im using if else statements and it has become way to hard to keep up with. I also have labels that i have to toggle with each chart so its getting out of control. Here is a small example of one of my else if statements.
else if (ddlApplication.SelectedItem.Text == "Rapp" && ddlTests.SelectedItem.Text == "Total Test Runs")
{
string query = string.Format("select TestName,Count (TestName) AS Counts from VExecutionGlobalHistory where TestTypeID = 2 group by TestName", ddlTests.SelectedItem.Value);
DataTable dt = GetData(query);
//Loop and add each datatable row to the Pie Chart Values
foreach (DataRow row in dt.Rows)
{
SpecificTestsRapp.PieChartValues.Add(new AjaxControlToolkit.PieChartValue
{
Category = row["TestName"].ToString(),
Data = Convert.ToDecimal(row["Counts"])
});
}
string SpecificTestsRappS = null;
string sql2 = "select Count (TestName) AS Counts from VExecutionGlobalHistory where TestTypeID = 2 ";
string connString2 = ";Initial Catalog=Performance;User ID=;Password=";
using (SqlConnection conn = new SqlConnection(connString2))
{
conn.Open();
using (SqlCommand command = new SqlCommand(sql2, conn))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
SpecificTestsRappS = reader[0].ToString();
lblTotalTestsRapp.Text = SpecificTestsRappS;
break;
}
}
conn.Close();
}
SpecificTestsRapp.ChartTitle = "Total Tests Run";
TotalTestsWeb6.Visible = false;
HoursWeb6.Visible = false;
TotalValidationsWeb6.Visible = false;
CostComparisonWeb6.Visible = false;
SpecificTestsWeb6.Visible = false;
TotalTestsRapp.Visible = false;
TotalValidationsRapp.Visible = false;
SpecificTestsRapp.Visible = true;
HoursRapp.Visible = false;
IONChart.Visible = false;
CostComparisonRapp.Visible = false;
txtTotalHoursRapp.Visible = false;
lblTotalHoursRapp.Visible = false;
txtTotalHoursRappA.Visible = false;
lblTotalHoursRappA.Visible = false;
txtTotalCostRappM.Visible = false;
lblTotalCostRappM.Visible = false;
txtTotalCostRappA.Visible = false;
lblTotalCostRappA.Visible = false;
txtTotalTestsRapp.Visible = true;
lblTotalTestsRapp.Visible = true;
lblTotalValidationsRapp.Visible = false;
txtTotalValidationsRapp.Visible = false;
lblTotalValidations.Visible = false;
txtTotalValidations.Visible = false;
lblTotalTests.Visible = false;
txtTotalTests.Visible = false;
txtTotalHours.Visible = false;
lblTotalHours.Visible = false;
txtTotalHoursA.Visible = false;
lblTotalHoursA.Visible = false;
txtTotalCostA.Visible = false;
lblTotalCostA.Visible = false;
txtTotalCostM.Visible = false;
lblTotalCostM.Visible = false;
Label1.Visible = false;
Label2.Visible = false;
}
Technically i will need 16 of these when im done since i have 16 charts. There has to be a more efficient way to do this. Any suggestions?
I'm thinking Startegy and Factory design patterns.
You could do something in the lines of:
In your UI:
var chartStartegyFactory = new ChartStrategyFactory();
var chartStategy = chartStartegyFactory.Create(ddlApplication.SelectedItem.Text, ddlTests.SelectedItem.Text);
var chart = chartStategy.CreateChart();
lblTotalTestsRapp.Text = chart.ChartData;
SpecificTestsRapp.ChartTitle = chart.ChartTitle;
TotalTestsWeb6.Visible = chart.TotalTestsWeb6Visible;
// continue assigning properties in your UI
In your business layer:
public class ChartStrategyFactory
{
public IChartStrategy Create(string application, string test)
{
if (application == "Rapp" && test == "Total Test Runs")
return new RappTotalTestsRunChartStrategy();
// add strategies for other charts
throw new NotSupportedException();
}
}
public interface IChartStrategy
{
Chart CreateChart();
}
public class Chart
{
public string ChartTitle { get; set; }
public string ChartData { get; set; }
public bool TotalTestsWeb6Visible { get; set; }
// create all properties you need
}
public class RappTotalTestsRunChartStrategy : IChartStrategy
{
public Chart CreateChart(){
Chart chart = new Chart();
chart.ChartData = GetDataFromDatabase();
chart.ChartTitle = "Your Chart Title";
chart.TotalTestsWeb6Visible = false;
// continue assigning properties
return chart;
}
}
Basically your Chart creation code will be encapsulated in each Startegy and you will gain extensibility (it suffices to modify your ChartStrategyFactory when a new chart is developed.
I have to wrote a DataGridView and filled it programmatically.
I want when the user searches the a word for example key and there is cell which contains it (for example its keyword) just highlight the searched word key in keyword not the all keyword or not the cell nor the row.
Here is the code for filling DataGridView:
private void Fill()
{
try
{
if (dataGridView1 != null)
{
dataGridView1.ColumnCount = 11;
dataGridView1.Columns[0].HeaderText = Resources.Form1_Fill_ID;
dataGridView1.Columns[1].HeaderText = Resources.Form1_Fill_Family;
dataGridView1.Columns[2].HeaderText = Resources.Form1_Fill_Cellphone;
dataGridView1.Columns[3].HeaderText = Resources.Form1_Fill_Phone1;
dataGridView1.Columns[4].HeaderText = Resources.Form1_Fill_Phone2;
dataGridView1.Columns[5].HeaderText = Resources.Form1_Fill_Phone3;
dataGridView1.Columns[6].HeaderText = Resources.Form1_Fill_Fax;
dataGridView1.Columns[7].HeaderText = Resources.Form1_Fill_CompanyName;
dataGridView1.Columns[8].HeaderText = Resources.Form1_Fill_Agency;
dataGridView1.Columns[9].HeaderText = Resources.Form1_Fill_Brands;
dataGridView1.Columns[10].HeaderText = Resources.Form1_Fill_Address;
dataGridView1.Columns[0].Name = Resources.Form1_Fill_ID;
dataGridView1.Columns[1].Name = Resources.Form1_Fill_Family;
dataGridView1.Columns[2].Name = Resources.Form1_Fill_Cellphone;
dataGridView1.Columns[3].Name = Resources.Form1_Fill_Phone1;
dataGridView1.Columns[4].Name = Resources.Form1_Fill_Phone2;
dataGridView1.Columns[5].Name = Resources.Form1_Fill_Phone3;
dataGridView1.Columns[6].Name = Resources.Form1_Fill_Fax;
dataGridView1.Columns[7].Name = Resources.Form1_Fill_CompanyName;
dataGridView1.Columns[8].Name = Resources.Form1_Fill_Agency;
dataGridView1.Columns[9].Name = Resources.Form1_Fill_Brands;
dataGridView1.Columns[10].Name = Resources.Form1_Fill_Address;
}
_conn.ConnectionString = _connectionString;
var cmd = new OleDbCommand("Select * from contacts ", _conn);
_conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
int i = 0;
while (reader != null && reader.Read())
{
if (dataGridView1 != null)
{
dataGridView1.Rows.Add(1);
}
if (dataGridView1 != null)
{
var row = dataGridView1.Rows[i];
row.Cells[Resources.Form1_Fill_ID].Value = reader[0].ToString();
row.Cells[Resources.Form1_Fill_Family].Value = reader[1].ToString();
row.Cells[Resources.Form1_Fill_Cellphone].Value = reader[2].ToString();
row.Cells[Resources.Form1_Fill_Phone1].Value = reader[3].ToString();
row.Cells[Resources.Form1_Fill_Phone2].Value = reader[4].ToString();
row.Cells[Resources.Form1_Fill_Phone3].Value = reader[5].ToString();
row.Cells[Resources.Form1_Fill_Fax].Value = reader[6].ToString();
row.Cells[Resources.Form1_Fill_CompanyName].Value = reader[7].ToString();
row.Cells[Resources.Form1_Fill_Agency].Value = reader[8].ToString();
row.Cells[Resources.Form1_Fill_Brands].Value = reader[9].ToString();
row.Cells[Resources.Form1_Fill_Address].Value = reader[10].ToString();
}
i++;
}
}
catch (Exception ex)
{
return;
}
finally
{
_conn.Close();
}
}
and here is the search code
private void searchBtn_Click(object sender, EventArgs e)
{
// Code to search the alphanumneric Part Number (in Column1 header called "PART NUMBER") and highlihgt the row
foreach (DataGridViewRow row in dataGridView1.Rows)
{
try
{
if (row.Cells[0].Value.ToString().Contains(searchTxt.Text))
//row.Cells[0].Style.ForeColor = Color.Red;
{
var t = row.Cells[0].Value.ToString();
}
if (row.Cells[1].Value.ToString().Contains(searchTxt.Text))
row.Cells[1].Style.ForeColor = Color.Red;
if (row.Cells[2].Value.ToString().Contains(searchTxt.Text))
row.Cells[2].Style.ForeColor = Color.Red;
if (row.Cells[3].Value.ToString().Contains(searchTxt.Text))
row.Cells[3].Style.ForeColor = Color.Red;
if (row.Cells[4].Value.ToString().Contains(searchTxt.Text))
row.Cells[4].Style.ForeColor = Color.Red;
if (row.Cells[5].Value.ToString().Contains(searchTxt.Text))
row.Cells[5].Style.ForeColor = Color.Red;
if (row.Cells[6].Value.ToString().Contains(searchTxt.Text))
row.Cells[6].Style.ForeColor = Color.Red;
if (row.Cells[7].Value.ToString().Contains(searchTxt.Text))
row.Cells[7].Style.ForeColor = Color.Red;
if (row.Cells[8].Value.ToString().Contains(searchTxt.Text))
row.Cells[8].Style.ForeColor = Color.Red;
if (row.Cells[9].Value.ToString().Contains(searchTxt.Text))
row.Cells[9].Style.ForeColor = Color.Red;
if (row.Cells[10].Value.ToString().Contains(searchTxt.Text))
row.Cells[10].Style.ForeColor = Color.Red;
}
catch (Exception)
{
return;
}
}
}
If this search is only depend upon client side loaded data then why don't you suggest to customer use browser search functionality.
If still you have to provide this functionality to customer then why you are going at server side code to do this task.... you can handle this in javascript.
Following are the example Link which explains about how to access datagridview in javascript.
http://www.netomatix.com/development/gridviewclientsideaccess.aspx
http://www.thescarms.com/dotnet/webdatagrid.aspx
It's not possible with standard .NET controls.
You can try Telerik winform suite or similar, which controls allowing to use HTML formatting to highlight only a part of the text.
Do you really need DataGridView? If you use it to display data only, you can also try using WebBrowser control and draw an html table there.
You should also refactor your search code:
for(int i=0; i<11; i++)
{
if (row.Cells[i].Value.ToString().Contains(searchTxt.Text))
row.Cells[i].Style.ForeColor = Color.Red;
}
I though the following code would work but every time I look at file.Item; it is null. Should I be doing something different?
Microsoft.Office.Server.Search.Query.FullTextSqlQuery query = new Microsoft.Office.Server.Search.Query.FullTextSqlQuery(siteCollection);
query.QueryText = "SELECT Title, Path, Description, Write, Rank, Size from scope() where \"scope\" = 'SocialNetworking'";
query.ResultTypes = Microsoft.Office.Server.Search.Query.ResultType.RelevantResults;
//query.RowLimit = Int32.MaxValue;
query.TrimDuplicates = true;
query.EnableStemming = false;
query.IgnoreAllNoiseQuery = true;
query.KeywordInclusion = Microsoft.Office.Server.Search.Query.KeywordInclusion.AllKeywords;
query.Timeout = 0x2710;
query.HighlightedSentenceCount = 3;
query.SiteContext = new Uri(siteCollection.Url);
query.AuthenticationType = Microsoft.Office.Server.Search.Query.QueryAuthenticationType.NtAuthenticatedQuery;
Microsoft.Office.Server.Search.Query.ResultTableCollection queryResults = query.Execute();
Microsoft.Office.Server.Search.Query.ResultTable queryResultsTable = queryResults[Microsoft.Office.Server.Search.Query.ResultType.RelevantResults];
DataTable queryDataTable = new DataTable();
queryDataTable.Load(queryResultsTable, LoadOption.OverwriteChanges);
foreach (DataRow dr in queryDataTable.Rows)
{
//if (dr["ContentType"].ToString() == "Item")
//{
using (SPSite lookupSite = new SPSite(dr["Path"].ToString()))
{
using (SPWeb web = lookupSite.OpenWeb())
{
SPFile file = web.GetFile(dr["Path"].ToString());
SPListItem li = file.Item;
}
}
//}
}
If you know it is an item try SPWeb.GetListItem
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.getlistitem.aspx
The file might also not exist, check SPFile.Exists before using any of SPFile's properties
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfile.exists.aspx