我知道这可能很简单,我用谷歌搜索但仍然无法看到我的错误。
我的基本代码是:
public static void postToImgur(string imagFilePath, string apiKey, string apiSecret, string title, string description)
{
byte[] imageData;
FileStream fileStream = File.OpenRead(imagFilePath);
imageData = new byte[fileStream.Length];
fileStream.Read(imageData, 0, imageData.Length);
fileStream.Close();
const int MAX_URI_LENGTH = 32766;
string base64img = System.Convert.ToBase64String(imageData);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < base64img.Length; i += MAX_URI_LENGTH)
{
sb.Append(Uri.EscapeDataString(base64img.Substring(i, Math.Min(MAX_URI_LENGTH, base64img.Length - i))));
}
string uploadRequestString = "client_id" + apiKey + "client_secret" + apiSecret + "&title=" + title + "&imageTitle" + title + "&description" + description + "&caption=" + title + "img" + "&image=" + sb.ToString();
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://api.imgur.com/3/upload.xml");
// needs a space between
webRequest.Headers.Add("Authorization", "Client-ID " + apiKey);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ServicePoint.Expect100Continue = false;
StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream());
streamWriter.Write(uploadRequestString);
streamWriter.Close();
WebResponse response = webRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
string responseString = responseReader.ReadToEnd();
//received response is a xml file. the link to the uploaded file is in between the tag< link ></ link >
//using regular expression to retrive the link to the image.
Regex regex = new Regex("<link>(.*)</link>");
var test = regex.Match(responseString).Groups[1].ToString();
//return regex.Match(responseString).Groups[1].ToString();
dgView.Rows.Add(test);
}
private void btnPostToImgur_Click(object sender, EventArgs e)
{
// validation
postToImgur(txtBoxImageLocation.Text, "ccc8d227d", "5b64c6b63908aa3e51840db3ce874137d7", txtBoxTitle.Text, txtBoxDescription.Text);
}
我收到了错误
访问非静态方法或者需要对象引用 属性
当我尝试将数据添加到dgView
我的datagrid变量名称时,我们将不胜感激。
答案 0 :(得分:3)
您的方法postToImgur
是一种静态方法。来自msdn:
静态方法和属性无法访问非静态字段和 包含类型的事件,他们无法访问实例 任何对象的变量,除非它在方法中显式传递 参数。
您已尝试使用
dgView.Rows.Add(test);
但是,您没有将DataGridView
对象作为参数传递,并且变量不是静态的 - 因此,您无法访问静态方法中的dgView
变量。
您的两个选择是:
postToImgur
非静态dgView
变量传递给方法